java的TCP通信

客户端


import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SendSocket {
    public static void main(String[] args) throws IOException {
        //创建对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 12345);

        //获取输出流
        OutputStream outputStream = socket.getOutputStream();

        //发送数据
        outputStream.write("Tcp我来发送数据了".getBytes());

        //关闭socket
        socket.close();
    }
}


服务端

package mystring.demo2;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ReviceSocket {
    public static void main(String[] args) throws IOException {
        //创建服务器对象
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket accept = serverSocket.accept();

        //获取输出流
        InputStream inputStream = accept.getInputStream();
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        System.out.println(new String(bytes,0,len));
        accept.close();
        serverSocket.close();
    }
}


posted @ 2021-05-02 19:34  code-G  阅读(179)  评论(0编辑  收藏  举报