一个项目看java TCP/IP Socket编程 - Java - New - JavaEye论坛
导读:
前一段时间刚做了个 java 程序和网络上多台机器的 c 程序通讯的项目,遵循的是 TCP/IP 协议,用到了 java 的 Socket 编程。网络通讯是 java 的强项,用 TCP/IP 协议可以方便的和网络上的其他程序互通消息。
先来介绍下网络协议:TCP/IPTransmission Control Protocol 传输控制协议Internet Protocol 互联网协议UDPUser 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 类
项目代码如下
Java 代码- 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.InetAddress;
- import java.net.InetSocketAddress;
- 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;
-
-
-
-
-
- publicclass SocketFactory {
- private Socket socket = null;
- private String targetIpAddress = null;
- privateint targetPort = 0;
- private InetAddress localIpAddress = null;
- public SocketFactory(String targetIpAddress, int targetPort) {
- try {
- connect(targetIpAddress, targetPort);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
- privatevoid connect(String targetIpAddress, int targetPort) throws UnknownHostException, IOException {
- if(socket != null && socket.isConnected() && ifConnectIpEqualsTargetIp(targetIpAddress)) {
- return;
- }
- setTargetIpAddress(targetIpAddress);
- setTargetPort(targetPort);
- localIpAddress = convertIpAddress(ReadConfig.localIpAddress);
- if(socket == null) {
- socket = new Socket(targetIpAddress, targetPort, localIpAddress, ReadConfig.localClientPort);
- return;
- }
- socket.connect(new InetSocketAddress(convertIpAddress(targetIpAddress), targetPort));
- }
-
-
-
-
- privateboolean ifConnectIpEqualsTargetIp(String targetIpAddress) {
- InetAddress connectIp = socket.getInetAddress();
- InetAddress targetIp = null;
- try {
- targetIp = convertIpAddress(targetIpAddress);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- return connectIp.equals(targetIp) ? true : false;
- }
-
-
-
-
- publicstaticvoid request(String commandType, String commandContent) {
- SocketFactory sf = new SocketFactory(ReadConfig.targetIpAddress, ReadConfig.targetPort);
- sf.sendRequest(commandType, commandContent);
- sf.new ServerThread(sf, commandType);
- }
-
-
-
-
- privatevoid sendRequest(String commandType, String commandContent) {
- OutputStream os = null;
- BufferedOutputStream bs = null;
- try {
- os = socket.getOutputStream();
- bs = new BufferedOutputStream(os);
- char[] message = MessageFactory.makeRequestMessage(targetIpAddress, 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 + "'", ReadConfig.commandStateShowLineCount);
- } catch (IOException e) {
- SwingUtils.appendLog(MainForm.jTextArea, "Error!!! 发送请求:'" + commandType + "''" + commandContent + "'失败!!" + e.getMessage(), ReadConfig.commandStateShowLineCount);
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
-
- }
- }
-
-
-
- privateboolean getResponse() {
- InputStream is = null;
- DataInputStream di = null;
- boolean returnFlag = false;
- try {
- is = socket.getInputStream();
- di = new DataInputStream(is);
- byte[] temp = newbyte[1];
- int flag = 0;
- ArrayList tempByteList = new ArrayList();
- int i = 0;
- while(flag != -1) {
- i++;
- flag = di.read(temp = newbyte[1]);
- if(flag != -1) tempByteList.add(temp);
- if(i == 38) break;
- }
- if(i == 1) {
- SwingUtils.Error("未收到 response!!!");
- returnfalse;
- }
- 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 = newbyte[1]);
- if(flag != -1) tempByteList.add(temp);
- if(i == 26) break;
- }
- byte[] length = newbyte[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 = newbyte[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;
- }
-
-
-
-
-
-
- privatevoid distributeMess(Message message) {
- String machineName = message.getMachineName();
- String programName = message.getProgramName();
- String processId = message.getProcessId();
- String messGrade = message.getMessageGrade();
- String content = message.getContent();
- String key = machineName + '|' + programName + '|' + processId;
- ArrayList messageList = (ArrayList) ListenerInvoke.messageMap.get(key);
- if(messageList == null) {
- messageList = new ArrayList();
- messageList.add(content);
- ListenerInvoke.messageMap.put(key, messageList);
- } else {
- synchronized(messageList) {
- messageList.add(content);
- if(!ReadConfig.threadDeleteMessCacheOrFIFO && messageList.size() >= ReadConfig.messageCacheSizeLimit)
- messageList.remove(0);
- }
- }
- ListenerInvoke.processStateMap.put(key, messGrade);
- if(!ListenerInvoke.messageMapKeyList.contains(key))
- ListenerInvoke.messageMapKeyList.add(key);
- }
-
-
-
- private Message getMessage() {
- InputStream is = null;
- DataInputStream di = null;
- Message message = null;
- try {
- is = this.socket.getInputStream();
- di = new DataInputStream(is);
- byte[] temp = newbyte[1];
- int flag = 0;
- ArrayList tempByteList = new ArrayList();
- int i = 0;
- while(flag != -1) {
- i++;
- flag = di.read(temp = newbyte[1]);
- if(flag != -1) tempByteList.add(temp);
- if(i == 38) break;
- }
- if (i == 1) returnnull;
- tempByteList = new ArrayList();
- i = 0;
- while(flag != -1) {
- i++;
- flag = di.read(temp = newbyte[1]);
- if(flag != -1) tempByteList.add(temp);
- if(i == 74) break;
- }
- byte[] length = newbyte[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 = newbyte[1]);
- if(flag == -1) break;
- tempByteList.add(temp);
- }
- message = MessageFactory.readMessage(tempByteList, len);
- SwingUtils.appendLog(MainForm.jTextArea, "收到新 Message", ReadConfig.commandStateShowLineCount);
- distributeMess(message);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- }
- return message;
- }
-
-
-
-
- class ServerThread implements Runnable {
- SocketFactory socketFactory;
- String commandType = null;
- Thread t;
- boolean flag = false;
- boolean ifFirstExec = true;
- privateboolean ifGetMessage = true;
- public ServerThread(SocketFactory socketFactory, String commandType) {
- this.socketFactory = socketFactory;
- this.commandType = commandType;
- t = new Thread(this);
- t.start();
- }
- publicvoid run() {
- try {
- while(ifGetMessage) {
- if(ifFirstExec) {
- flag = socketFactory.getResponse();
- ifFirstExec = false;
- }
- if(flag) {
- if(commandType.equalsIgnoreCase(MessageFactory.SCAN_COMMAND) && socket != null) socketFactory.getMessage();
- else {
- stopThread();
- }
- } else {
- stopThread();
- }
- Thread.sleep(ReadConfig.getMessageThreadSleep);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- publicvoid stopThread() {
- try {
- socketFactory.closeSocket();
- socketFactory = null;
- ifGetMessage = false;
- this.t.join(100);
- } catch (InterruptedException ex) {
- System.out.println("socket 服务器线程终止异常!!!");
- } finally {
- t = null;
- }
- }
- }
-
-
-
-
-
- private InetAddress convertIpAddress(String ipAddress) throws UnknownHostException {
- byte[] temp = newbyte[4];
- String [] tempIp = ipAddress.trim().split("//.");
- for(int i = 0; i <tempIp.length; i++) {
- temp[i] = (byte)(Integer.parseInt(tempIp[i]));
- }
- return InetAddress.getByAddress(temp);
- }
-
-
- privatevoid closeSocket() {
- try {
- if(!socket.isClosed()) socket.close();
- socket = null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
- public String getTargetIpAddress() {
- return targetIpAddress;
- }
-
-
- publicvoid setTargetIpAddress(String targetIpAddress) {
- this.targetIpAddress = targetIpAddress;
- }
-
-
- publicint getTargetPort() {
- return targetPort;
- }
-
-
- publicvoid setTargetPort(int targetPort) {
- this.targetPort = targetPort;
- }
- }
- 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.InetAddress;
-
- import java.net.InetSocketAddress;
-
- 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套接字工厂,对外接口是静态方法request(String, String)
-
- * Copyright: Copyright (c) 2008
-
- * @author cuishen
-
- * @version 1.0
-
- */
-
- public class
来源: http://lib.csdn.net/article/embeddeddevelopment/41982