Java Network Programming - basic steps TCP protocol

The TCP:
the TCP protocol based on the request - response pattern
using transmission data stream implementation io

Create a server
1, specify the port to use to create a ServerSocket server
2, blocking wait for a connection accept, there is a accept to set up a client
3, Operation: io stream
4, free up resources

 public class tcp {

static void main public (String [] args) throws IOException
{
    System.out.println ( "Server ----- -----");
    //. 1, the designated port to use to create the server ServerSocket
        ServerSocket server = new ServerSocket ( 8888);

    // 2, waits for a connection blocking Accept
        Socket = server.accept Client (); // returns a Socket object
        System.out.println ( "a client establishes a connection");
    // 3, operation: io stream
        DataInputStream dis = new DataInputStream (client.getInputStream ()) ; // input,
        client.getInputStream () returns a byte input stream

        String data=dis.readUTF();
        System.out.println(data);
    // 4、释放资源
        dis.close();
        client.close();

        server.close();

    }
}

Create a client
1, to establish a connection: Socket created using the address and port of the client service +
2: Enter the output stream operation
3, the release of resources

 public class tcp2 {

static void main public (String [] args) throws IOException
{
    System.out.println ( "Client -------- ---------");
    //. 1, connection is established: Use Socket + create a client service address and port
    the Socket = new new Client2 the Socket ( "localhost", 8888);
    // 2, operation: operation of the input and output streams
    DataOutputStream dos = new DataOutputStream (client2.getOutputStream ( )); // output

    String data = "Du Yulong most handsome";
    dos.writeUTF (the Data);
    dos.flush ();
    // 3, release resources
    dos.close ();
    client2.close ();

}
}

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160359.htm