java tcp/ip socket编程

来源:互联网 发布:欧陆风云3 mac 汉化 编辑:程序博客网 时间:2024/03/29 15:05
 前一段时间刚做了个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类

项目代码如下

Java代码 复制代码
  1. package com.sse.monitor.serv;  
  2.   
  3. import java.io.DataInputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.BufferedOutputStream;  
  8.   
  9. import java.net.Socket;  
  10. import java.net.UnknownHostException;  
  11. import java.util.ArrayList;  
  12.   
  13. import com.sse.monitor.bean.Message;  
  14. import com.sse.monitor.bean.MessageHead;  
  15. import com.sse.monitor.bean.ResponseMessage;  
  16. import com.sse.monitor.form.ListenerInvoke;  
  17. import com.sse.monitor.form.MainForm;  
  18. import com.sse.monitor.util.SwingUtils;  
  19.   
  20. /** 
  21.  * Socket套接字工厂,对外接口是静态方法request(String, String, String, int)  
  22.  * Copyright: Copyright (c) 2008  
  23.  * Company: conserv 
  24.  * @author cuishen 
  25.  * @version 1.2 
  26.  */  
  27. public class SocketFactory {  
  28.     private Socket socket = null;  
  29.     private String targetIpAddress = null;  
  30.     private int targetPort = 0;  
  31.     private static SocketFactory sf = new SocketFactory();  
  32.   
  33.     public SocketFactory() {  
  34.     }  
  35.   
  36.     /** 
  37.      * 建立一条TCP/IP连接 
  38.      * @param targetIpAddress String 目标ip地址 
  39.      * @param targetPort String 目标端口 
  40.      * @throws IOException 
  41.      */  
  42.     private void connect(String targetIpAddress, int targetPort) throws IOException {  
  43.         setTargetIpAddress(targetIpAddress);  
  44.         setTargetPort(targetPort);  
  45.         if(socket == null)  
  46.             socket = new Socket(targetIpAddress, targetPort);  
  47.     }  
  48.   
  49.     /** 
  50.      * 这是对外接口。发送命令,接收反馈和接收message放两个线程, 
  51.      * 发送命令并接收反馈是短连接,所以每次执行成功后,将销毁socket并终止线程, 
  52.      * 接收message是长连接,所以可能会new出n个线程,建议对接收message的线程做缓存 
  53.      * @param commandType String 命令类型 
  54.      * @param commandContent String 命令内容 
  55.      * @param targetIP String 目标ip 
  56.      * @param targetPort int 目标端口 
  57.      */  
  58.     public static void request(String commandType, String commandContent, String targetIP, int targetPort) {  
  59.         if (commandType.equalsIgnoreCase(MessageFactory.SCAN_COMMAND)) {  
  60.             sf.new GetMessageSocketThread(commandType, commandContent, targetIP, targetPort);  
  61.         } else {  
  62.             sf.new RequestSocketThread(commandType, commandContent, targetIP, targetPort);  
  63.         }  
  64.     }  
  65.   
  66.     /** 
  67.      * 发送请求 
  68.      * @param commandType String 命令类型 
  69.      * @param commandContent String 命令内容 
  70.      * @param targetIp String 目标ip 
  71.      */  
  72.     private void sendRequest(String commandType, String commandContent, String targetIp) {  
  73.         OutputStream os = null;  
  74.         BufferedOutputStream bs = null;  
  75.         try {  
  76.             os = socket.getOutputStream();  
  77.             bs = new BufferedOutputStream(os);  
  78.             char[] message = MessageFactory.makeRequestMessage(targetIp, commandType, commandContent, MessageFactory.COMMAND_TRADE_CODE, MessageFactory.RIGHT_COMMAND, MessageFactory.MESSAGE_END_FLAG);  
  79.             for (int i = 0; i < message.length; i++)  
  80.                 bs.write(new String(message).getBytes(), i, 1);  
  81.             bs.flush();  
  82.             SwingUtils.appendLog(MainForm.jTextArea, "发送请求:'" + commandType + "' '" + commandContent + "' '" + targetIp + "'", ReadConfig.commandStateShowLineCount);  
  83.         } catch (IOException e) {  
  84.             SwingUtils.appendLog(MainForm.jTextArea, "Error!!! 发送请求:'" + commandType + "' '" + commandContent + "' '" + targetIp + "'失败!! " + e.getMessage(), ReadConfig.commandStateShowLineCount);  
  85.             e.printStackTrace();  
  86.         } catch (Exception e) {  
  87.             e.printStackTrace();  
  88.         } finally {  
  89.         }  
  90.     }  
  91.   
  92.     /** 
  93.      * 获得反馈 
  94.      *  
  95.      * @return 如果成功获得反馈,则返回true;否则返回false 
  96.      */  
  97.     private boolean getResponse() {  
  98.         InputStream is = null;  
  99.         DataInputStream di = null;  
  100.         boolean returnFlag = false;  
  101.         try {  
  102.             is = socket.getInputStream();  
  103.             di = new DataInputStream(is);  
  104.             byte[] temp = new byte[1];  
  105.             int flag = 0;  
  106.             ArrayList tempByteList = new ArrayList();  
  107.             int i = 0;  
  108.             while (flag != -1) {  
  109.                 i++;  
  110.                 flag = di.read(temp = new byte[1]);  
  111.                 if (flag != -1)  
  112.                     tempByteList.add(temp);  
  113.                 if (i == 38)  
  114.                     break;  
  115.             }  
  116.             if (i == 1) {  
  117.                 SwingUtils.Error("未收到response!!!");  
  118.                 return false;  
  119.             }  
  120.             MessageHead messageHead = MessageFactory.readHead(tempByteList);  
  121.   
  122.             SwingUtils.appendLog(MainForm.jTextArea, "收到 response", ReadConfig.commandStateShowLineCount);  
  123.   
  124.             tempByteList = new ArrayList();  
  125.             i = 0;  
  126.             while (flag != -1) {  
  127.                 i++;  
  128.                 flag = di.read(temp = new byte[1]);  
  129.                 if (flag != -1)  
  130.                     tempByteList.add(temp);  
  131.                 if (i == 26)  
  132.                     break;  
  133.             }  
  134.             byte[] length = new byte[4];  
  135.             di.read(length);  
  136.             int len = Integer.parseInt(new String(length, MessageFactory.DEFAULT_CHAR_SET).trim());  
  137.             flag = 0;  
  138.             for (int j = 0; j < (len + 37); j++) {  
  139.                 flag = di.read(temp = new byte[1]);  
  140.                 if (flag == -1)  
  141.                     break;  
  142.                 tempByteList.add(temp);  
  143.             }  
  144.   
  145.             ResponseMessage rm = MessageFactory.readResponseMessage(tempByteList, len);  
  146.   
  147.             if (messageHead.getErrorCode().equals(MessageFactory.SUCCESS))  
  148.                 returnFlag = true;  
  149.             else  
  150.                 SwingUtils.Error("errorCode: " + messageHead.getErrorCode() + "; content: " + rm.getCommandContent());  
  151.         } catch (IOException e) {  
  152.             e.printStackTrace();  
  153.         } finally {  
  154.         }  
  155.         return returnFlag;  
  156.     }  
  157.   
  158.     /** 
  159.      * 分发消息的方法,将消息按进程名发送到对应的消息缓存 
  160.      * 消息缓存ListenerInvoke.messageMap,key = machineName + '|' + programName + '|' + processId, value = messageList 
  161.      * 存放messageMap里面的键名的List -- ListenerInvoke.messageMapKeyList 
  162.      * 进程状态缓存ListenerInvoke.processStateMap, key = machineName + '|' + programName + '|' + processId, value = String 
  163.      * @param message Message 
  164.      */  
  165.     private void distributeMess(Message message) {  
  166.         String machineName = message.getMachineName();  
  167.         String programName = message.getProgramName();  
  168.         String processId = message.getProcessId();  
  169.         String messGrade = message.getMessageGrade();  
  170.         String content = message.getContent();  
  171.         String key = machineName + '|' + programName + '|' + processId;  
  172.         ArrayList messageList = (ArrayList) ListenerInvoke.messageMap.get(key);  
  173.         if (messageList == null) {  
  174.             messageList = new ArrayList();  
  175.             messageList.add(content);  
  176.             ListenerInvoke.messageMap.put(key, messageList);  
  177.         } else {  
  178.             synchronized (messageList) {  
  179.                 messageList.add(content);  
  180.                 if (!ReadConfig.threadDeleteMessCacheOrFIFO  
  181.                         && messageList.size() >= ReadConfig.messageCacheSizeLimit)  
  182.                     messageList.remove(0);  
  183.             }  
  184.         }  
  185.         ListenerInvoke.processStateMap.put(key, messGrade);  
  186.         if (!ListenerInvoke.messageMapKeyList.contains(key))  
  187.             ListenerInvoke.messageMapKeyList.add(key);  
  188.     }  
  189.   
  190.     /** 
  191.      * 接收message 
  192.      * @return Message 
  193.      */  
  194.     private boolean getMessage() {  
  195.         InputStream is = null;  
  196.         DataInputStream di = null;  
  197.         Message message = null;  
  198.         try {  
  199.             if (this.socket == null)  return false;  
  200.             is = this.socket.getInputStream();  
  201.             if (is == null)  return false;  
  202.             di = new DataInputStream(is);  
  203.             byte[] temp = new byte[1];  
  204.             int flag = 0;  
  205.             ArrayList tempByteList = new ArrayList();  
  206.             int i = 0;  
  207.             while (flag != -1) {  
  208.                 i++;  
  209.                 flag = di.read(temp = new byte[1]);  
  210.                 if (flag != -1)  
  211.                     tempByteList.add(temp);  
  212.                 if (i == 38)  
  213.                     break;  
  214.             }  
  215.             if (i == 1)  return false;  
  216.   
  217.             tempByteList = new ArrayList();  
  218.             i = 0;  
  219.             while (flag != -1) {  
  220.                 i++;  
  221.                 flag = di.read(temp = new byte[1]);  
  222.                 if (flag != -1)  
  223.                     tempByteList.add(temp);  
  224.                 if (i == 74)  
  225.                     break;  
  226.             }  
  227.             byte[] length = new byte[4];  
  228.             di.read(length);  
  229.             int len = Integer.parseInt(new String(length,  
  230.                     MessageFactory.DEFAULT_CHAR_SET).trim());  
  231.             flag = 0;  
  232.             for (int j = 0; j < len; j++) {  
  233.                 flag = di.read(temp = new byte[1]);  
  234.                 if (flag == -1)  
  235.                     break;  
  236.                 tempByteList.add(temp);  
  237.             }  
  238.             message = MessageFactory.readMessage(tempByteList, len);  
  239.             SwingUtils.appendLog(MainForm.jTextArea, "收到新 Message",  
  240.                     ReadConfig.commandStateShowLineCount);  
  241.             distributeMess(message);// 分发message  
  242.         } catch (IOException e) {  
  243.             e.printStackTrace();  
  244.         } finally {  
  245.         }  
  246.         return true;  
  247.     }  
  248.   
  249.     /** 
  250.      * 负责发送请求接收反馈的内部线程类,每new一个RequestSocketThread线程, 
  251.      * 就new一个socket,建立一条专属连接,成功接收反馈后将销毁socket,终止线程。 
  252.      * 将发送请求,接收反馈放进内部线程处理,是为了防止套接字阻塞造成主线程挂死。 
  253.      * @author cuishen 
  254.      * @version 1.2 
  255.      */  
  256.     class RequestSocketThread implements Runnable {  
  257.         private SocketFactory socketFactory;  
  258.         private String commandType = null;  
  259.         private String commandContent = null;  
  260.         private String targetIP = null;  
  261.         Thread t;  
  262.   
  263.         public RequestSocketThread(String commandType, String commandContent, String targetIP, int targetPort) {  
  264.             this.socketFactory = new SocketFactory();  
  265.             try {  
  266.                 this.socketFactory.connect(ReadConfig.targetIpAddress, ReadConfig.targetPort);  
  267.             } catch (UnknownHostException e) {  
  268.                 SwingUtils.Error("主机 IP 地址无法确定,无法建立连接! targetIP=" + ReadConfig.targetIpAddress + ", targetPort=" + ReadConfig.targetPort);  
  269.                 e.printStackTrace();  
  270.             } catch (IOException e) {  
  271.                 SwingUtils.Error("访问被拒绝,无法建立连接,请检查网络! targetIP=" + ReadConfig.targetIpAddress + ", targetPort=" + ReadConfig.targetPort);  
  272.                 e.printStackTrace();  
  273.             }  
  274.             this.commandType = commandType;  
  275.             this.commandContent = commandContent;  
  276.             this.targetIP = targetIP;  
  277.             t = new Thread(this);  
  278.             t.start();  
  279.         }  
  280.   
  281.         public void run() {  
  282.             this.socketFactory.sendRequest(commandType, commandContent, targetIP);  
  283.             this.socketFactory.getResponse();  
  284.             stopThread();  
  285.         }  
  286.   
  287.         public void stopThread() {  
  288.             try {  
  289.                 this.commandType = null;  
  290.                 this.commandContent = null;  
  291.                 this.targetIP = null;  
  292.                 socketFactory.closeSocket();  
  293.                 socketFactory = null;  
  294.                 this.t.join(100);  
  295.             } catch (InterruptedException e) {  
  296.                 e.printStackTrace();  
  297.             } finally {  
  298.                 t = null;  
  299.             }  
  300.         }  
  301.     }  
  302.   
  303.     /** 
  304.      * 负责接收message的内部线程类,每new一个GetMessageSocketThread线程, 
  305.      * 就new一个socket,建立一条专属TCP/IP连接,getMessage是长连接,所以建议 
  306.      * 将该线程放入缓存方便管理 
  307.      * @author cuishen 
  308.      * @version 1.2 
  309.      */  
  310.     class GetMessageSocketThread implements Runnable {  
  311.         private SocketFactory socketFactory;  
  312.         private String commandType = null;  
  313.         private String commandContent = null;  
  314.         private String targetIP = null;  
  315.         Thread t;  
  316.         private boolean flag = false;  
  317.         private boolean ifGetResponse = true;  
  318.         private boolean ifGetMessage = false;  
  319.         private boolean ifSendRequest = true;  
  320.         private boolean ifCycle = true;  
  321.   
  322.         public GetMessageSocketThread(String commandType, String commandContent, String targetIP, int targetPort) {  
  323.               
  324.             this.socketFactory = new SocketFactory();  
  325.             try {  
  326.                 this.socketFactory.connect(ReadConfig.targetIpAddress, ReadConfig.targetPort);  
  327.             } catch (UnknownHostException e) {  
  328.                 SwingUtils.Error("主机 IP 地址无法确定,无法建立连接! targetIP="  
  329.                         + ReadConfig.targetIpAddress + ", targetPort="  
  330.                         + ReadConfig.targetPort);  
  331.                 e.printStackTrace();  
  332.             } catch (IOException e) {  
  333.                 SwingUtils.Error("访问被拒绝,无法建立连接,请检查网络! targetIP="  
  334.                         + ReadConfig.targetIpAddress + ", targetPort="  
  335.                         + ReadConfig.targetPort);  
  336.                 e.printStackTrace();  
  337.             }  
  338.             this.commandType = commandType;  
  339.             this.commandContent = commandContent;  
  340.             this.targetIP = targetIP;  
  341.             t = new Thread(this);  
  342.             t.start();  
  343.         }  
  344.   
  345.         public void run() {  
  346.             while (ifCycle) {  
  347.                 if (ifSendRequest) {  
  348.                     this.socketFactory.sendRequest(commandType, commandContent, targetIP);  
  349.                     ifSendRequest = false;  
  350.                 }  
  351.                 if (ifGetResponse) {  
  352.                     flag = socketFactory.getResponse();  
  353.                     ifGetResponse = false;  
  354.                 }  
  355.                 if (flag && ifGetMessage && socketFactory.socket != null) {  
  356.                     if (!socketFactory.getMessage()) {  
  357.                         try {  
  358.                             Thread.sleep(ReadConfig.getMessageThreadSleep);  
  359.                         } catch (InterruptedException e) {  
  360.                             e.printStackTrace();  
  361.                         }  
  362.                     }  
  363.                 }  
  364.             }  
  365.         }  
  366.   
  367.         public void stopThread() {  
  368.             try {  
  369.                 this.commandType = null;  
  370.                 this.commandContent = null;  
  371.                 this.targetIP = null;  
  372.                 ifGetMessage = false;  
  373.                 ifCycle = false;  
  374.                 socketFactory.closeSocket();  
  375.                 socketFactory = null;  
  376.                 this.t.join(100);  
  377.             } catch (InterruptedException e) {  
  378.                 e.printStackTrace();  
  379.             } finally {  
  380.                 t = null;  
  381.             }  
  382.         }  
  383.     }  
  384.   
  385.     /** 
  386.      * 关闭套接字 
  387.      */  
  388.     private void closeSocket() {  
  389.         try {  
  390.             if (!socket.isClosed())  
  391.                 socket.close();  
  392.             socket = null;  
  393.         } catch (IOException e) {  
  394.             e.printStackTrace();  
  395.         }  
  396.     }  
  397.   
  398.     /** 
  399.      * @return the targetIpAddress 
  400.      */  
  401.     public String getTargetIpAddress() {  
  402.         return targetIpAddress;  
  403.     }  
  404.   
  405.     /** 
  406.      * @param targetIpAddress 
  407.      *            the targetIpAddress to set 
  408.      */  
  409.     public void setTargetIpAddress(String targetIpAddress) {  
  410.         this.targetIpAddress = targetIpAddress;  
  411.     }  
  412.   
  413.     /** 
  414.      * @return the targetPort 
  415.      */  
  416.     public int getTargetPort() {  
  417.         return targetPort;  
  418.     }  
  419.   
  420.     /** 
  421.      * @param targetPort 
  422.      *            the targetPort to set 
  423.      */  
  424.     public void setTargetPort(int targetPort) {  
  425.         this.targetPort = targetPort;  
  426.     }  
  427.   
  428. }  


以上是Socket编程,ServerSocket在项目里没有用到,但是我也写了个包装类供参考
Java代码 复制代码
  1. package com.sse.monitor.serv;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.ServerSocket;  
  5. import java.net.Socket;  
  6.   
  7. /** 
  8.  * 服务器套接字工厂 
  9.  * Copyright: Copyright (c) 2008 
  10.  * @author cuishen 
  11.  * @version 1.0 
  12.  */  
  13. public class ServerSocketFactory {  
  14.     private static ServerSocket server;  
  15.     private static Socket client;  
  16.     private boolean ifRunServer = true;  
  17.       
  18.     public void runServer(int port) throws IOException {  
  19.         //本地建立一个套接字服务器,等待其他机器访问  
  20.         server = new ServerSocket(port);  
  21.         System.out.println("Socket Server Start...");  
  22.         new ServerThread();  
  23.     }  
  24.       
  25.   
  26.     class ServerThread implements Runnable {  
  27.         Thread t;  
  28.           
  29.         public ServerThread() {  
  30.             t = new Thread(this);  
  31.             t.start();  
  32.         }  
  33.   
  34.         public void run() {  
  35.             try {  
  36.                 while(ifRunServer) {  
  37.                     if(client == null) client = server.accept();  
  38.                     if(client != null//getMessage();  
  39.                     Thread.sleep(ReadConfig.serverThreadSleep);  
  40.                 }  
  41.             } catch (InterruptedException e) {  
  42.                 e.printStackTrace();  
  43.             }   
  44.             catch (IOException e) {  
  45.                 e.printStackTrace();  
  46.             }  
  47.         }  
  48.         public void stopThread() {  
  49.             try {  
  50.                 ifRunServer = false;  
  51.                 this.t.join(100);  
  52.             } catch (InterruptedException ex) {  
  53.                 System.out.println("socket服务器线程终止异常!!!");  
  54.             } finally {  
  55.                 t = null;  
  56.             }  
  57.         }  
  58.     }  
  59. }  


Socket编程就是运用Socket或者ServerSocket类搭配线程来使用(由于TCP/IP属于可靠性传输,不会丢包)。可能会因为在发送请求或者接受消息时Socket阻塞而导致主线程挂死,因此发送请求、接收消息的方法要放进子线程里处理;对于同一目标ip和端口,在同一个子线程里只能new一个Socket,也就是说,要对同一地址建立多条连接,就要开启多个线程。而且注意连接可能会因作用不同分长连接和短连接,要分别处理,本项目中发送请求和接受message就分别属于短连接和长连接,因此分别开发了RequestSocketThread和GetMessageSocketThread两个子线程区分对待。可以同时开发个Message类来封装打包和解包消息的方法(项目中开发MessageFactory.java),方便调用
原创粉丝点击