Demonstrate TCP transmission
1. TCP sub-client and server
2. The client corresponds to a socket. The server object is serversocket.
Client:
By checking the socket object, we can find that when this object is created, we can connect to the specified host.
Because TCP is connection-oriented, when a socket service is established, a server must exist and the connection is successful.
After the channel is established, data is transmitted through the channel.
Import Java. io. *; import java.net. *; public class tcpclient {public static void main (string [] ARGs) throws exception {// create the socket service of the client, specify the target host and port socket S = new socket ("169.254.74.22", 10009); // to send data, you must obtain the output stream outputstream out = s in the socket. getoutputstream (); out. write ("TCP Ge men lai le ". getbytes (); S. close ();}}
Requirement: Define the terminal to receive data and print it on the console
Server:
1. Create a socket for the serverProgram, Serversocket.
And listen to a port
2. Obtain the client object connected to the client through the serversocket accept Method
Therefore, this method is blocking.
3. If the client sends data, the server must use the corresponding client object and obtain
Read the data sent from the read stream of the client object and print it on the console.
Import Java. io. *; import java.net. *; public class tcpserver {public static void main (string [] ARGs) throws exception {// create a server socket service and listen to a port serversocket Ss = new serversocket (10009 ); // obtain the client object connected by using the accept method. Socket S = ss. accept (); string IP = S. getinetaddress (). gethostaddress (); system. out. println (IP + ".... connected "); // obtain the data sent from the client, you must use the corresponding read stream of the client to read the data. Inputstream in = S. getinputstream (); byte [] Buf = new byte [1024]; int Len = in. read (BUF); system. out. println (new string (BUF, 0, Len); S. close (); SS. close ();}}