一个项目看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类 

项目代码如下 

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套接字工厂,对外接口是静态方法 SocketFactory.request(String, String, String, int)  
  22.  * Copyright: Copyright (c) 2008  
  23.  * Company: conserv 
  24.  * @author cuishen 
  25.  * @version 1.3 
  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;  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值