一,网络编程中两个主要的问题
一个是如何准确的定位网络上一台或多台主机,另一个就是找到主机后如何可靠高效的进行数据传输。
在TCP/IP协议中IP层主要负责网络主机的定位,数据传输的路由,由IP地址可以唯一地确定Internet上的一台主机。
而TCP层则提供面向应用的可靠(tcp)的或非可靠(UDP)的数据传输机制,这是网络编程的主要对象,一般不需要关心IP层是如何处理数据的。
目前较为流行的网络编程模型是客户机/服务器(C/S)结构。即通信双方一方作为服务器等待客户提出请求并予以响应。客户则在需要服务时向服务器提 出申请。服务器一般作为守护进程始终运行,监听网络端口,一旦有客户请求,就会启动一个服务进程来响应该客户,同时自己继续监听服务端口,使后来的客户也 能及时得到服务。
二,两类传输协议:TCP;UDP
TCP是Tranfer Control Protocol的 简称,是一种面向连接的保证可靠传输的协议。通过TCP协议传输,得到的是一个顺序的无差错的数据流。发送方和接收方的成对的两个socket之间必须建 立连接,以便在TCP协议的基础上进行通信,当一个socket(通常都是server socket)等待建立连接时,另一个socket可以要求进行连接,一旦这两个socket连接起来,它们就可以进行双向数据传输,双方都可以进行发送 或接收操作。
UDP是User Datagram Protocol的简称,是一种无连接的协议,每个数据报都是一个独立的信息,包括完整的源地址或目的地址,它在网络上以任何可能的路径传往目的地,因此能否到达目的地,到达目的地的时间以及内容的正确性都是不能被保证的。
比较:
UDP:1,每个数据报中都给出了完整的地址信息,因此无需要建立发送方和接收方的连接。
2,UDP传输数据时是有大小限制的,每个被传输的数据报必须限定在64KB之内。
3,UDP是一个不可靠的协议,发送方所发送的数据报并不一定以相同的次序到达接收方
TCP:1,面向连接的协议,在socket之间进行数据传输之前必然要建立连接,所以在TCP中需要连接
时间。
2,TCP传输数据大小限制,一旦连接建立起来,双方的socket就可以按统一的格式传输大的
数据。
3,TCP是一个可靠的协议,它确保接收方完全正确地获取发送方所发送的全部数据。
应用:
1,TCP在网络通信上有极强的生命力,例如远程连接(Telnet)和文件传输(FTP)都需要不定长度的数据被可靠地传输。但是可靠的传输是要付出代价的,对数据内容正确性的检验必然占用计算机的处理时间和网络的带宽,因此TCP传输的效率不如UDP高。
2,UDP操作简单,而且仅需要较少的监护,因此通常用于局域网高可靠性的分散系统中client/server应用程序。例如视频会议系统,并不要求音频视频数据绝对的正确,只要保证连贯性就可以了,这种情况下显然使用UDP会更合理一些。
三,基于Socket的java网络编程
1,什么是Socket
网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket。Socket通常用来实现客户方和服务方的连接。Socket是TCP/IP协议的一个十分流行的编程界面,一个Socket由一个IP地址和一个端口号唯一确定。
但是,Socket所支持的协议种类也不光TCP/IP一种,因此两者之间是没有必然联系的。在Java环境下,Socket编程主要是指基于TCP/IP协议的网络编程。
2,Socket通讯的过程
Server端Listen(监听)某个端口是否有连接请求,Client端向Server 端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client 端都可以通过Send,Write等方法与对方通信。
对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:
(1) 创建Socket;
(2) 打开连接到Socket的输入/出流;
(3) 按照一定的协议对Socket进行读/写操作;
(4) 关闭Socket.(在实际应用中,并未使用到显示的close,虽然很多文章都推荐如此,不过在我的程序中,可能因为程序本身比较简单,要求不高,所以并未造成什么影响。)
3,创建Socket
创建Socket
java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用很方便。其构造方法如下:
Socket(InetAddress address, int port);
Socket(InetAddress address, int port, boolean stream);
Socket(String host, int prot);
Socket(String host, int prot, boolean stream);
Socket(SocketImpl impl)
Socket(String host, int port, InetAddress localAddr, int localPort)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog, InetAddress bindAddr)
其中address、host和port分别是双向连接中另一方的IP地址、主机名和端 口号,stream指明socket是流socket还是数据报socket,localPort表示本地主机的端口号,localAddr和 bindAddr是本地机器的地址(ServerSocket的主机地址),impl是socket的父类,既可以用来创建serverSocket又可 以用来创建Socket。count则表示服务端所能支持的最大连接数。例如:学习视频网 http://www.xxspw.com
Socket client = new Socket("127.0.01.", 80);
ServerSocket server = new ServerSocket(80);
注意,在选择端口时,必须小心。每一个端口提供一种特定的服务,只有给出正确的端口,才 能获得相应的服务。0~1023的端口号为系统所保留,例如http服务的端口号为80,telnet服务的端口号为21,ftp服务的端口号为23, 所以我们在选择端口号时,最好选择一个大于1023的数以防止发生冲突。
在创建socket时如果发生错误,将产生IOException,在程序中必须对之作出处理。所以在创建Socket或ServerSocket是必须捕获或抛出例外。
4,简单的Client/Server程序
1. 客户端程序
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
//向本机的4700端口发出客户请求
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
String readline;
readline=sin.readLine(); //从系统标准输入读入一字符串
while(!readline.equals("bye")){
//若从标准输入读入的字符串为 "bye"则停止循环
os.println(readline);
//将从系统标准输入读入的字符串输出到Server
os.flush();
//刷新输出流,使Server马上收到该字符串
System.out.println("Client:"+readline);
//在系统标准输出上打印读入的字符串
System.out.println("Server:"+is.readLine());
//从Server读入一字符串,并打印到标准输出上
readline=sin.readLine(); //从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e); //出错,则打印出错信息
}
}
}
2. 服务器端程序
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
//创建一个ServerSocket在端口4700监听客户请求
}catch(Exception e) {
System.out.println("can not listen to:"+e);
//出错,打印出错信息
}
Socket socket=null;
try{
socket=server.accept();
//使用accept()阻塞等待客户请求,有客户
//请求到来则产生一个Socket对象,并继续执行
}catch(Exception e) {
System.out.println("Error."+e);
//出错,打印出错信息
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
PrintWriter os=newPrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
System.out.println("Client:"+is.readLine());
//在标准输出上打印从客户端读入的字符串
line=sin.readLine();
//从标准输入读入一字符串
while(!line.equals("bye")){
//如果该字符串为 "bye",则停止循环
os.println(line);
//向客户端输出该字符串
os.flush();
//刷新输出流,使Client马上收到该字符串
System.out.println("Server:"+line);
//在系统标准输出上打印读入的字符串
System.out.println("Client:"+is.readLine());
//从Client读入一字符串,并打印到标准输出上
line=sin.readLine();
//从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
server.close(); //关闭ServerSocket
}catch(Exception e){
System.out.println("Error:"+e);
//出错,打印出错信息
}
}
}
5,支持多客户的client/server程序
前面的Client/Server程序只能实现Server和一个客户的对话。在实际应用 中,往往是在服务器上运行一个永久的程序,它可以接收来自其他多个客户端的请求,提供相应的服务。为了实现在服务器方给多个客户提供服务的功能,需要对上 面的程序进行改造,利用多线程实现多客户机制。服务器总是在指定的端口上监听是否有客户请求,一旦监听到客户请求,服务器就会启动一个专门的服务线程来响 应该客户的请求,而服务器本身在启动完线程之后马上又进入监听状态,等待下一个客户的到来。
原文链接: http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html
一个项目看java TCP/IP Socket编程(1.3版)
前一段时间刚做了个java程序和网络上多台机器的c程序通讯的项目,遵循的是TCP/IP协议,用到了java的Socket编程。网络通讯是java的强项,用TCP/IP协议可以方便的和网络上的其他程序互通消息。
先来介绍下网络协议:
TCP/IP
Transmission Control Protocol 传输控制协议
Internet Protocol 互联网协议
UDP
User Datagram Protocol 用户数据协议
连接协议:
分为:
面向连接协议: Connection Oriented Protocol
非连接协议: Connectionless Protocol
1).面向连接协议是指两台电脑在传输数据前,先会建立一个专属的连接。就如电信局的交换机会为打电话双方提供专属连接一样。
Internet上的面向连接协议就是TCP/IP
特点:确认回应;分组序号;流量控制。
TCP/IP属于可靠性传输,适合不容许有传输错误的网络程序设计使用
2).非连接协议:无专属连接,无分组,容错,距离短,可同时对多台电脑进行数据传输
Internet上的非连接协议就是UDP
TCP在网络通信上有极强的生命力,例如远程连接(Telnet)和文件传输(FTP)都需要不定长度的数据被可靠地传输。相比之下UDP操作简单,而且仅需要较少的监护,因此通常用于局域网高可靠性的分散系统中client/server应用程序。
Socket 是程序与网络间的一种接口,大部分网络应用程序都是点对点的,所谓点就是服务器端和客户端所执行的程序。Socket是用来接收和传送分组的一个端点。
java的Socket编程要用到java.net包,最常用的是net包下的6个类:InetAddress(互联网协议 (IP) 地址)类,Socket(套接字)类,ServerSocket(套接字服务器)类,DatagramSocket(发送和接收数据报包的套接字)类,DatagramPacket(数据报包)类,MulticastSocket(多播数据报套接字类用于发送和接收 IP 多播包)类,其中InetAddress、Socket、ServerSocket类是属于TCP面向连接协议,DatagramSocket、DatagramPacket和MulticastSocket类则属于UDP非连接协议的传送类。
本项目因为使用TCP/IP协议,主要用到Socket和ServerSocket类
项目代码如下
- package com.sse.monitor.serv;
- import java.io.DataInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.BufferedOutputStream;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import com.sse.monitor.bean.Message;
- import com.sse.monitor.bean.MessageHead;
- import com.sse.monitor.bean.ResponseMessage;
- import com.sse.monitor.form.ListenerInvoke;
- import com.sse.monitor.form.MainForm;
- import com.sse.monitor.util.SwingUtils;
- /**
- * Socket套接字工厂,对外接口是静态方法 SocketFactory.request(String, String, String, int)
- * Copyright: Copyright (c) 2008
- * Company: conserv
- * @author cuishen
- * @version 1.3
- */
- public class SocketFactory {
- private Socket socket = null;
- private String targetIpAddress = null;
- private int targetPort = 0;
- private static SocketFactory sf = new SocketFactory();
- public SocketFactory() {
- }
- /**
- * 建立一条TCP/IP连接
- * @param targetIpAddress String 目标ip地址
- * @param targetPort String 目标端口
- * @throws IOException
- */
- private void connect(String targetIpAddress, int targetPort) throws IOException {
- setTargetIpAddress(targetIpAddress);
- setTargetPort(targetPort);
- if(socket == null)
- socket = new Socket(targetIpAddress, targetPort);
- }
- /**
- * 这是对外接口。发送命令,接收反馈和接收message放两个线程,
- * 发送命令并接收反馈是短连接,所以每次执行成功后,将销毁socket并终止线程,
- * 接收message是长连接,所以可能会new出n个线程,建议对接收message的线程做缓存
- * @param commandType String 命令类型
- * @param commandContent String 命令内容
- * @param targetIP String 目标ip
- * @param targetPort int 目标端口
- */
- public static void request(String commandType, String commandContent, String targetIP, int targetPort) {
- if (commandType.equalsIgnoreCase(MessageFactory.SCAN_COMMAND)) {
- sf.new GetMessageSocketThread(commandType, commandContent, targetIP, targetPort);
- } else {
- sf.new RequestSocketThread(commandType, commandContent, targetIP, targetPort);
- }
- }
- /**
- * 发送请求
- * @param commandType String 命令类型
- * @param commandContent String 命令内容
- * @param targetIp String 目标ip
- */
- private void sendRequest(String commandType, String commandContent, String targetIp) {
- OutputStream os = null;
- BufferedOutputStream bs = null;
- try {
- os = socket.getOutputStream();
- bs = new BufferedOutputStream(os);
- char[] message = MessageFactory.makeRequestMessage(targetIp, commandType, commandContent, MessageFactory.COMMAND_TRADE_CODE, MessageFactory.RIGHT_COMMAND, MessageFactory.MESSAGE_END_FLAG);
- for (int i = 0; i < message.length; i++)
- bs.write(new String(message).getBytes(), i, 1);
- bs.flush();
- SwingUtils.appendLog(MainForm.jTextArea, "发送请求:'" + commandType + "' '" + commandContent + "' '" + targetIp + "'", ReadConfig.commandStateShowLineCount);
- } catch (IOException e) {
- SwingUtils.appendLog(MainForm.jTextArea, "Error!!! 发送请求:'" + commandType + "' '" + commandContent + "' '" + targetIp + "'失败!! " + e.getMessage(), ReadConfig.commandStateShowLineCount);
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- }
- }
- /**
- * 获得反馈
- *
- * @return 如果成功获得反馈,则返回true;否则返回false
- */
- private boolean getResponse() {
- InputStream is = null;
- DataInputStream di = null;
- boolean returnFlag = false;
- try {
- is = socket.getInputStream();
- di = new DataInputStream(is);
- byte[] temp = new byte[1];
- int flag = 0;
- ArrayList tempByteList = new ArrayList();
- int i = 0;
- while (flag != -1) {
- i++;
- flag = di.read(temp = new byte[1]);
- if (flag != -1)
- tempByteList.add(temp);
- if (i == 38)
- break;
- }
- if (i == 1) {
- SwingUtils.Error("未收到response!!!");
- return false;
- }
- MessageHead messageHead = MessageFactory.readHead(tempByteList);
- SwingUtils.appendLog(MainForm.jTextArea, "收到 response", ReadConfig.commandStateShowLineCount);
- tempByteList = new ArrayList();
- i = 0;
- while (flag != -1) {
- i++;
- flag = di.read(temp = new byte[1]);
- if (flag != -1)
- tempByteList.add(temp);
- if (i == 26)
- break;
- }
- byte[] length = new byte[4];
- di.read(length);
- int len = Integer.parseInt(new String(length, MessageFactory.DEFAULT_CHAR_SET).trim());
- flag = 0;
- for (int j = 0; j < (len + 37); j++) {
- flag = di.read(temp = new byte[1]);
- if (flag == -1)
- break;
- tempByteList.add(temp);
- }
- ResponseMessage rm = MessageFactory.readResponseMessage(tempByteList, len);
- if (messageHead.getErrorCode().equals(MessageFactory.SUCCESS))
- returnFlag = true;
- else
- SwingUtils.Error("errorCode: " + messageHead.getErrorCode() + "; content: " + rm.getCommandContent());
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- }
- return returnFlag;
- }
- /**
- * 分发消息的方法,将消息按进程名发送到对应的消息缓存
- *
- * 消息缓存ListenerInvoke.messageMap,key = machineName +
- * '|' + programName + '|' + processId, value = messageList
- * 存放messageMap里面的键名的List -- ListenerInvoke.messageMapKeyList
- * 进程状态缓存ListenerInvoke.processStateMap, key = machineName + '|' +
- * programName + '|' + processId, value = String
- *
- * @param message Message
- */
- private void distributeMess(Message message) {
- String machineName = message.getMachineName();
- String programName = message.getProgramName();
- String processId = message.getProcessId();
- String content = message.getContent();
- String key = machineName + '|' + programName + '|' + processId;
- key = key.trim();
- ArrayList messageList = null;
- if (ListenerInvoke.messageMap.get(key) == null) {
- synchronized (ListenerInvoke.messageMap) {
- if (ListenerInvoke.messageMap.get(key) == null) {
- messageList = new ArrayList();
- messageList.add(content);
- ListenerInvoke.messageMap.put(key, messageList);
- }
- }
- } else {
- messageList = (ArrayList) ListenerInvoke.messageMap.get(key);
- synchronized (messageList) {
- if (ListenerInvoke.messageMap.get(key) != null) {
- messageList.add(content);
- if (!ReadConfig.threadDeleteMessCacheOrFIFO
- && messageList.size() >= ReadConfig.messageCacheSizeLimit)
- messageList.remove(0);
- }
- }
- }
- if (!ListenerInvoke.messageMapKeyList.contains(key)) {
- synchronized (ListenerInvoke.messageMapKeyList) {
- if (!ListenerInvoke.messageMapKeyList.contains(key))
- ListenerInvoke.messageMapKeyList.add(key);
- }
- }
- }
- /**
- * 接收message
- * @return Message
- */
- private boolean getMessage() {
- InputStream is = null;
- DataInputStream di = null;
- Message message = null;
- try {
- if (this.socket == null) return false;
- is = this.socket.getInputStream();
- if (is == null) return false;
- di = new DataInputStream(is);
- byte[] temp = new byte[1];
- int flag = 0;
- ArrayList tempByteList = new ArrayList();
- int i = 0;
- while (flag != -1) {
- i++;
- flag = di.read(temp = new byte[1]);
- if (flag != -1)
- tempByteList.add(temp);
- if (i == 38)
- break;
- }
- if (i == 1) return false;
- tempByteList = new ArrayList();
- i = 0;
- while (flag != -1) {
- i++;
- flag = di.read(temp = new byte[1]);
- if (flag != -1)
- tempByteList.add(temp);
- if (i == 74)
- break;
- }
- byte[] length = new byte[4];
- di.read(length);
- int len = Integer.parseInt(new String(length,
- MessageFactory.DEFAULT_CHAR_SET).trim());
- flag = 0;
- for (int j = 0; j < len; j++) {
- flag = di.read(temp = new byte[1]);
- if (flag == -1)
- break;
- tempByteList.add(temp);
- }
- message = MessageFactory.readMessage(tempByteList, len);
- SwingUtils.appendLog(MainForm.jTextArea, "收到新 Message",
- ReadConfig.commandStateShowLineCount);
- distributeMess(message);// 分发message
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- }
- return true;
- }
- /**
- * 负责发送请求接收反馈的内部线程类,每new一个RequestSocketThread线程,
- * 就new一个socket,建立一条专属连接,成功接收反馈后将销毁socket,终止线程。
- * 将发送请求,接收反馈放进内部线程处理,是为了防止套接字阻塞造成主线程挂死。
- * @author cuishen
- * @version 1.2
- */
- class RequestSocketThread implements Runnable {
- private SocketFactory socketFactory;
- private String commandType = null;
- private String commandContent = null;
- private String targetIP = null;
- Thread t;
- public RequestSocketThread(String commandType, String commandContent, String targetIP, int targetPort) {
- this.socketFactory = new SocketFactory();
- try {
- this.socketFactory.connect(ReadConfig.targetIpAddress, ReadConfig.targetPort);
- } catch (UnknownHostException e) {
- SwingUtils.Error("主机 IP 地址无法确定,无法建立连接! targetIP=" + ReadConfig.targetIpAddress + ", targetPort=" + ReadConfig.targetPort);
- e.printStackTrace();
- } catch (IOException e) {
- SwingUtils.Error("访问被拒绝,无法建立连接,请检查网络! targetIP=" + ReadConfig.targetIpAddress + ", targetPort=" + ReadConfig.targetPort);
- e.printStackTrace();
- }
- this.commandType = commandType;
- this.commandContent = commandContent;
- this.targetIP = targetIP;
- t = new Thread(this);
- t.start();
- }
- public void run() {
- this.socketFactory.sendRequest(commandType, commandContent, targetIP);
- this.socketFactory.getResponse();
- stopThread();
- }
- public void stopThread() {
- try {
- this.commandType = null;
- this.commandContent = null;
- this.targetIP = null;
- socketFactory.closeSocket();
- socketFactory = null;
- this.t.join(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- t = null;
- }
- }
- }
- /**
- * 负责接收message的内部线程类,每new一个GetMessageSocketThread线程,
- * 就new一个socket,建立一条专属TCP/IP连接,getMessage是长连接,所以建议
- * 将该线程放入缓存方便管理
- * @author cuishen
- * @version 1.2
- */
- class GetMessageSocketThread implements Runnable {
- private SocketFactory socketFactory;
- private String commandType = null;
- private String commandContent = null;
- private String targetIP = null;
- Thread t;
- private boolean flag = false;
- private boolean ifGetResponse = true;
- private boolean ifGetMessage = true;
- private boolean ifSendRequest = true;
- private boolean ifCycle = true;
- public GetMessageSocketThread(String commandType, String commandContent, String targetIP, int targetPort) {
- this.socketFactory = new SocketFactory();
- try {
- this.socketFactory.connect(ReadConfig.targetIpAddress, ReadConfig.targetPort);
- } catch (UnknownHostException e) {
- SwingUtils.Error("主机 IP 地址无法确定,无法建立连接! targetIP="
- + ReadConfig.targetIpAddress + ", targetPort="
- + ReadConfig.targetPort);
- e.printStackTrace();
- } catch (IOException e) {
- SwingUtils.Error("访问被拒绝,无法建立连接,请检查网络! targetIP="
- + ReadConfig.targetIpAddress + ", targetPort="
- + ReadConfig.targetPort);
- e.printStackTrace();
- }
- this.commandType = commandType;
- this.commandContent = commandContent;
- this.targetIP = targetIP;
- t = new Thread(this);
- t.start();
- }
- public void run() {
- while (ifCycle) {
- if (ifSendRequest) {
- this.socketFactory.sendRequest(commandType, commandContent, targetIP);
- ifSendRequest = false;
- }
- if (ifGetResponse) {
- flag = socketFactory.getResponse();
- ifGetResponse = false;
- }
- if (flag && ifGetMessage && socketFactory.socket != null) {
- if (!socketFactory.getMessage()) {
- try {
- Thread.sleep(ReadConfig.getMessageThreadSleep);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- public void stopThread() {
- try {
- this.commandType = null;
- this.commandContent = null;
- this.targetIP = null;
- ifGetMessage = false;
- ifCycle = false;
- socketFactory.closeSocket();
- socketFactory = null;
- this.t.join(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- t = null;
- }
- }
- }
- /**
- * 关闭套接字
- */
- private void closeSocket() {
- try {
- if (!socket.isClosed())
- socket.close();
- socket = null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * @return the targetIpAddress
- */
- public String getTargetIpAddress() {
- return targetIpAddress;
- }
- /**
- * @param targetIpAddress
- * the targetIpAddress to set
- */
- public void setTargetIpAddress(String targetIpAddress) {
- this.targetIpAddress = targetIpAddress;
- }
- /**
- * @return the targetPort
- */
- public int getTargetPort() {
- return targetPort;
- }
- /**
- * @param targetPort
- * the targetPort to set
- */
- public void setTargetPort(int targetPort) {
- this.targetPort = targetPort;
- }
- }
以上是Socket编程,ServerSocket在项目里没有用到,但是我也写了个包装类供参考
- package com.sse.monitor.serv;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * 服务器套接字工厂
- * Copyright: Copyright (c) 2008
- * @author cuishen
- * @version 1.0
- */
- public class ServerSocketFactory {
- private static ServerSocket server;
- private static Socket client;
- private boolean ifRunServer = true;
- public void runServer(int port) throws IOException {
- //本地建立一个套接字服务器,等待其他机器访问
- server = new ServerSocket(port);
- System.out.println("Socket Server Start...");
- new ServerThread();
- }
- class ServerThread implements Runnable {
- Thread t;
- public ServerThread() {
- t = new Thread(this);
- t.start();
- }
- public void run() {
- try {
- while(ifRunServer) {
- if(client == null) client = server.accept();
- if(client != null) //getMessage();
- Thread.sleep(ReadConfig.serverThreadSleep);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void stopThread() {
- try {
- ifRunServer = false;
- this.t.join(100);
- } catch (InterruptedException ex) {
- System.out.println("socket服务器线程终止异常!!!");
- } finally {
- t = null;
- }
- }
- }
- }
http://cuishen.iteye.com/blog/242842
http://blog.youkuaiyun.com/kongxx/article/details/7259465
上一篇文章说到怎样写一个最简单的Java Socket通信,但是在上一篇文章中的例子有一个问题就是Server只能接受一个Client请求,当第一个Client连接后就占据了这个位置,后续Client不能再继续连接,所以需要做些改动,当Server没接受到一个Client连接请求之后,都把处理流程放到一个独立的线程里去运行,然后等待下一个Client连接请求,这样就不会阻塞Server端接收请求了。每个独立运行的程序在使用完Socket对象之后要将其关闭。具体代码如下:
- package com.googlecode.garbagecan.test.socket.sample2;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class MyServer {
- public static void main(String[] args) throws IOException {
- ServerSocket server = new ServerSocket(10000);
- while (true) {
- Socket socket = server.accept();
- invoke(socket);
- }
- }
- private static void invoke(final Socket client) throws IOException {
- new Thread(new Runnable() {
- public void run() {
- BufferedReader in = null;
- PrintWriter out = null;
- try {
- in = new BufferedReader(new InputStreamReader(client.getInputStream()));
- out = new PrintWriter(client.getOutputStream());
- while (true) {
- String msg = in.readLine();
- System.out.println(msg);
- out.println("Server received " + msg);
- out.flush();
- if (msg.equals("bye")) {
- break;
- }
- }
- } catch(IOException ex) {
- ex.printStackTrace();
- } finally {
- try {
- in.close();
- } catch (Exception e) {}
- try {
- out.close();
- } catch (Exception e) {}
- try {
- client.close();
- } catch (Exception e) {}
- }
- }
- }).start();
- }
- }
- package com.googlecode.garbagecan.test.socket.sample2;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class MyClient {
- public static void main(String[] args) throws Exception {
- Socket socket = new Socket("localhost", 10000);
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter out = new PrintWriter(socket.getOutputStream());
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- while (true) {
- String msg = reader.readLine();
- out.println(msg);
- out.flush();
- if (msg.equals("bye")) {
- break;
- }
- System.out.println(in.readLine());
- }
- socket.close();
- }
- }