Java网络编程TCP通信

TCP服务端

import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            Socket socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            String data = new String(bytes, 0, len);
            System.out.println("收到数据:" + data);

            socket.close();
            serverSocket.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

TCP客户端

import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {
    public static void main(String[] args) {

        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 8888);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("哈哈,我来了".getBytes());
            socket.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
posted @ 2020-12-30 23:09  xl4ng  阅读(61)  评论(0编辑  收藏  举报