• Java基础(basis)-----TCP通信


       1. TCP通信

    1.1 一对一通信

    服务端

    package com.practice;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * 服务端
     * 
     * @author yyx 2019年8月31日
     */
    public class TcpServer {
        public static void main(String[] args) {
            Socket socket = null;
            ServerSocket serverSocket = null;
            // 输入流
            InputStream inputStream = null;
            // 输出流
            OutputStream outputStream = null;
            try {
                serverSocket = new ServerSocket(8888);
                System.out.println("等待客户端连接!");
                socket = serverSocket.accept();
    
                inputStream = socket.getInputStream();
                byte[] b = new byte[1024];
                int len;
                while ((len = inputStream.read(b)) != -1) {
                    String str = new String(b, 0, len);
                    System.out.print(str);
                }
    
                outputStream = socket.getOutputStream();
                outputStream.write("客户端您好,我是服务端".getBytes());
    
                inputStream.close();
                outputStream.close();
                socket.close();
                serverSocket.close();
            } catch (Exception ex) {
    
            }
        }
    }

    客户端

    package com.practice;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    
    /**
     * 客户端
     * 
     * @author yyx 2019年8月31日
     */
    public class TcpClient {
        public static void main(String[] args) {
            Socket socket = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                socket = new Socket("127.0.0.1", 8888);
                outputStream = socket.getOutputStream();
                System.out.println("等待服务端回应");
                outputStream.write("我是客户端,请多关照".getBytes());
                // shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
                socket.shutdownOutput();
    
                System.out.println("**********************");
                inputStream = socket.getInputStream();
                byte[] b = new byte[1024];
                int len;
                while ((len = inputStream.read(b)) != -1) {
                    String str = new String(b, 0, len);
                    System.out.print(str);
                }
    
                inputStream.close();
                outputStream.close();
                socket.close();
            } catch (Exception ex) {
            }
        }
    }
  • 相关阅读:
    一个基础的C#的ACCESS操作类
    ASP.NET常用的三十三种实用代码
    在ASP.NET中使用MD5和SHA1加密
    一个比较漂亮的DataGrid样式表
    微软的面试题
    打印自定义纸张大小
    ASP.Net(C#)连接Oracle数据库的方法
    C#正则表达式应用范例
    matlab 字符串处理函数
    centos语言设置
  • 原文地址:https://www.cnblogs.com/fengfuwanliu/p/11403766.html
Copyright © 2020-2023  润新知