TCP客户端服务器

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/*
1.创建一个客户端对象Socket,构造方法绑定服务器的IP地址和端口号
2.使用socket对象中的方法getOutputStream()获取网络字节输出流outputstream对象
3.使用网络字节输出流output stream对象中的方法write,给服务器发送数据
4.使用Socket对象中的方法getInputStream()获取网络字节输入流InputStream对象
5.使用网络字节输入流InputStream对象中的方法read,读取服务器写回的数据
6.释放资源(Socket)

注意:
1.客户端和服务器端进行交互,必须使用Socket中提供的网络流,不能使用自己创建的流对象
2.当我们创建客户对象socket时候,就会去请求服务器和服务器经过三次握手连接通路
        如果没有启动抛出异常。
        如果启动则可以交互。

 */
public class Demo01TCPClient {
    public static void main(String[] args) throws IOException {
        Socket socket=new Socket("127.0.0.1",8888);
        OutputStream os=socket.getOutputStream();
        os.write("你好服务器".getBytes());
        InputStream is = socket.getInputStream();
        byte[] bytes=new byte[1024];
        int len=is.read(bytes);
        System.out.println(new String(bytes,0,len));

        socket.close();
    }

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

public class Demo02TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(8888);
        Socket socket=server.accept();
        InputStream is=socket.getInputStream();

        byte[] bytes=new byte[1024];
        int len=is.read(bytes);
        System.out.println(new String(bytes,0,len));
        OutputStream os = socket.getOutputStream();

        os.write("收到谢谢".getBytes());
        socket.close();
        server.close();
    }
}
原文地址:https://www.cnblogs.com/cy2268540857/p/13828514.html