TCP软件和硬件交互网络控制-.JAVA版本

该博客展示了如何使用Java实现一个TCP服务器,该服务器监听9000端口并接收客户端连接。服务器接收到连接后,会发送图片文件到客户端,并能接收客户端数据。代码中包含了读取流的方法和日志记录。提供了源码下载链接以及TCP测试工具下载链接。

TCP软件和硬件交互网络控制-.JAVA版本,底层原理是socket传输 默认服务端端口是9000 自己配置JDK以及java环境 在bin文件夹 cmd运行 java 【文件名】【如果想要客户端连接服务端的版本,后续更新。。。】

java版本配置需电脑有java环境,运行都是cmd程序

public class TestTcpServer extends Thread{
    Socket clientSocket;
    OutputStream outstream;
    InputStream instream;
    byte[] bytetime;
    boolean isconnect=false;
    int delaytime=25;
    String key="";
    public TestTcpServer(String guid,Socket clientSocket) {
        super();
        this.key=guid;
        isconnect=true;
        this.clientSocket = clientSocket;
    }
    @Override
      public void run() {
        try {
            //获得客户端的ip地址和主机名
            String clientAddress = clientSocket.getInetAddress().getHostAddress();
            String clientHostName = clientSocket.getInetAddress().getHostName();
            String port = clientSocket.getPort()+""; 
            System.out.println(clientHostName + "(" + clientAddress + ")" + " 连接成功!");
            System.out.println("Now, 传输数据...........");
            DataHelper.logMsg(clientHostName + "(" + clientAddress + ")" + " 连接成功!"); 
            long startTime = System.currentTimeMillis();
            //获取客户端的OutputStream
            outstream = clientSocket.getOutputStream();
            //传出图片数据 
            GetData();
            FileInputStream in = new FileInputStream(new File("home/wanhe.png"));
            byte[] data = new byte[4096];
            int length = 0;
            while((length = in.read(data)) != -1){
                outstream.write(data, 0, length);
                //写出数据
            }
            long endTime = System.currentTimeMillis();
            //提示信息
            System.out.println(clientHostName + "(" + clientAddress + ")" + " 数据传输成功," + "用时:" + ((endTime-startTime)) + "ms");
            DataHelper.logMsg(clientHostName + "(" + clientAddress + ")" + " 数据传输成功," + "用时:" + ((endTime-startTime)) + "ms");
            //关闭资源
            in.close();
            instream=clientSocket.getInputStream();
            while(isstart&&isconnect){
                
                try { 
                    if(clientSocket.isConnected()){
                    byte[] b= readStream(instream);
                    if(b!=null){ 
                        System.out.println("IP:["+clientAddress+";端口["+port+"][数据抓取:["+ByteArrayToHexString(b)+"]"); 
                        DataHelper.logMsg("IP:["+clientAddress+";端口["+port+"][数据抓取:["+ByteArrayToHexString(b)+"]");
                    }
                    else if(delaytime--<0){
                        delaytime=25;
                        if(bytetime==null){
                            bytetime=new byte[1];
                             bytetime[0]=0;
                        }
                        try{
                        outstream.write(bytetime);
                        }catch(Exception e){ 
                            isconnect=false;
                                clientSocket.close();
                                hash.remove(key);
                                 System.out.println("----IP:["+clientAddress+";端口["+port+"]关闭----------设备总数:["+hash.size()+"]");
                                 DataHelper.logMsg("----IP:["+clientAddress+";端口["+port+"]关闭----------设备总数:["+hash.size()+"]");
                        }
                        
                    }
                    Thread.sleep(200);
                    }
                    else{ 
                        isconnect=false;
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                     e.printStackTrace();
                    isconnect=false;
                    clientSocket.close();
                    hash.remove(key);
                    System.out.println("IP:["+clientAddress+";端口["+port+"]关闭----------设备总数:["+hash.size()+"]");
                   DataHelper.logMsg("IP:["+clientAddress+";端口["+port+"]关闭----------设备总数:["+hash.size()+"]");
                }
                
            }
            //clientSocket.close();
            System.out.println("连接关闭!");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    static String token="test";
    static boolean isstart=false; 
    static HashMap<String,TestTcpServer> hash;
    static ServerSocket tcpServer=null;
    /**
     * 启动入口
     * 
     * @param args
     */
    public static void main(String[] args) {
        
        try {
              //建立TCP连接服务,绑定端口
            int port=9000;
            isstart=true;
            hash=new HashMap<String,TestTcpServer>();
              tcpServer = new ServerSocket(port);
            System.out.println("开启端口["+port+"]...........");
            DataHelper.logMsg("开启端口["+port+"]...........");
//            stopGracefully(); 
            System.out.println("stopGracefully01...........");
               DataHelper.logMsg("stopGracefully01...........");
            Runtime.getRuntime().addShutdownHook(new Thread(){
                public void run() {
                   try {
                       System.out.println("stopGracefully02...........");
                       DataHelper.logMsg("stopGracefully02...........");
                     for (String data : hash.keySet()) {
                         if(data!=null&&hash.get(data).isconnect&&hash.get(data).clientSocket.isConnected()){
                             hash.get(data).isstart=false;
                             hash.get(data).clientSocket.close(); 
                         } 
                     }
                     hash.clear(); 
                        tcpServer.close();
                         System.out.println("stopGracefully03...........");
                               DataHelper.logMsg("stopGracefully03...........");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
        });
            //接受连接,传数据给连接的客户端,每个TCP连接都是一个java线程
            while(isstart){
                try{
                    if(!tcpServer.isClosed()){
                Socket clientSocket = tcpServer.accept();
                String guid=UUID.randomUUID().toString();
                TestTcpServer client= new TestTcpServer(guid,clientSocket); 
                client.start();
                hash.put(guid,client);
                System.out.println("...........设备连接...........设备总数:["+hash.size()+"]...........");
                DataHelper.logMsg("...........设备连接...........设备总数:["+hash.size()+"]...........");
                    }
                }catch(Exception e){ 
                    System.out.println("报错1:"+e.toString()+"...........");
                }
            }  
            System.out.println(".....主线程关闭...........");
            for (String data : hash.keySet()) {
                if(data!=null&&hash.get(data).isconnect&&hash.get(data).clientSocket.isConnected()){
                     hash.get(data).isstart=false;
                     hash.get(data).clientSocket.close(); 
                 } 
             }
            hash.clear();
            if(!tcpServer.isClosed())
            tcpServer.close();  
            System.out.println(".....主线程关闭2...........");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();  
            System.out.println("报错:"+e.toString()+"...........");
        } 
    }
    /**
     * @功能 读取流
     * @param inStream
     * @return 字节数组
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        int count = 0; 
            count = inStream.available(); 
        if(count==0)
            return null;
        byte[] b = new byte[count];
        inStream.read(b);
        return b;
    }
    public static void GetData(){
         File file=new File("home/wanhe.png");
         if(!file.exists()){
             file.mkdirs();
         }
         try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
    /**
     * 捕获系统退出
     * 目前没有效果
     */
    public static void stopGracefully() {
         System.out.println("stopGracefully01...........");
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
            @Override
            public void run() {
               try {
                   System.out.println("stopGracefully02...........");
                 for (String data : hash.keySet()) {
                     if(data!=null&&hash.get(data).isAlive()){
                         hash.get(data).stop();    
                     } 
                 }
                 hash.clear(); 
                    tcpServer.close();
                     System.out.println("stopGracefully03...........");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }));
}
    public static void startHook()
    {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run()
            {
                System.out.println("Execute Hook.....");
            }
        }));
    }
     // converts byte arrays to string字节数组转换字符串
    public static String ByteArrayToHexString(byte[] inarray) {
       int i, j, in;
       String[] hex = {
               "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"
       };
       String out = "";
       for (j = 0; j < inarray.length; ++j) {
           in = inarray[j] & 0xff;
           i = (in >> 4) & 0x0f;
           out += hex[i];
           i = in & 0x0f;
           out += hex[i]+" ";
       }
       return out;
   }

}


源码地址:https://download.csdn.net/download/dapeng2513/18232608

测试tcp工具地址:https://download.csdn.net/download/dapeng2513/18232893

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值