Bootstrap

java 学习疑问 01

实现TCP服务与客户端的交互

TCPClient中的代码:

public class TCPClient {

    public static void main(String[] args) throws IOException {
        Socket socket=new Socket("127.0.0.1",5053);
        OutputStream os = socket.getOutputStream();
        os.write("Hello!TCPServer.".getBytes());

        InputStream is=socket.getInputStream();
        byte[] b=new byte[1024];
        int len=is.read(b);
        System.out.println(new String(b,0,len));
		os.close();
        socket.close();
    }
}

TCPServer中代码:

public class TCPServer {

    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(5053);

        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("get!Thanks.".getBytes());

        socket.close();
        server.close();
    }
}


;