Author: Ching
Original address: http://blog.csdn.net/qingdujun/article/details/39322613
This article demonstrates that TCP uses a socket for network communication, which enables round-trip sending of data between client and server.
1) The client, sends a message to the server, and prints the received server message to the client console.
2) The server, accepts the client message, and prints it to the client at the beginning of the console, and also replies to the message received.
Client, the code is as follows:
Package Tcp.client2.qdj;import Java.io.inputstream;import Java.io.outputstream;import Java.net.Socket;public class CTcpClient2 {public static void main (string[] args) throws Exception {//Create Client Socket service, specify destination host and port. Socket s = new socket ("127.0.0.1", 6823); SYSTEM.OUT.PRINTLN ("Client has established a link ...");//Send data, you should get the output stream in the socket stream. OutputStream out = S.getoutputstream (); Out.write ("Hello to the server". GetBytes ());//Get the data sent by the servers, first get the input stream inputstream in = S.getinputstream (); byte[] buf = new byte[1024];//Note: Read will produce a blocking int len = In.read (BUF);// Print the amount of data sent by the server on the console System.out.println (new String (Buf,0,len));//Close Resource s.close ();}}
service side, the code is as follows:
Package Tcp.server2.qdj;import Java.io.inputstream;import Java.io.outputstream;import java.net.ServerSocket;import Java.net.socket;public class CTcpServer2 {public static void main (string[] args) throws Exception {//Set up a service-side Socket service, And listen for a port. ServerSocket ss = new ServerSocket (6823);//Get the Client object System.out.println ("server started, listening on 6823 ports, waiting for data ...") through the Accept method; Socket s = ss.accept ();//Get IP address string ip = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected");//Get the data sent by the client, then use the read stream of the client's object to read the data inputstream in = S.getinputstream (); byte[] buf = new byte[1024];//Note: Read will produce a blocking int len = In.read (BUF); System.out.println (New String (Buf,0,len));//Send message to client, get output stream outputstream out = S.getoutputstream (); Out.write ("Server received , you are also good ". GetBytes ());//Close client s.close ();//close server (optional) ss.close ();}}
Note that some of the text will cause blocking, it is because of the blocking, so that the data can be sent and accepted without error.
Operating effect:
1) Start the server side
2) Start the client
3) At this time the server side, displayed as follows
References: Java video Bi Xiangdong presenter
Original address: http://blog.csdn.net/qingdujun/article/details/39322613
Java TCP uses the socket for network communication (4) round-trip sending