Author: Ching
Original address: http://blog.csdn.net/qingdujun/article/details/39322051
This article demonstrates that TCP uses the socket for network communication, establishes a simple client, and uses the client to send a message to the server, which is then printed on the console after the service has received it.
1) The client sends a message to the server.
2) The server, receives the message to the client and prints it on the console.
Client, the code is as follows:
Package Tcp.clinet.qdj;import Java.io.outputstream;import JAVA.NET.SOCKET;//TCP Communication Client public class Ctcpclient {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", 6877); SYSTEM.OUT.PRINTLN ("Client has established a link ...");//In order to send data, you should get the output stream in the socket stream. OutputStream out = S.getoutputstream (); Out.write ("TCP Data Comes ...".) GetBytes ());//Close Resource s.close ();}}
service side, the code is as follows:
Package Tcp.server.qdj;import Java.io.inputstream;import Java.net.serversocket;import java.net.Socket;// The service side of the TCP communication class Cserver {public static void main (string[] args) throws exception{//establishes the service-side socket service and listens on a port. ServerSocket ss = new ServerSocket (6877);//Get the Client object System.out.println ("server started, listening on 6876 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];int len = In.read (BUF); System.out.println (New String (Buf,0,len));//Close client s.close ();//close server (optional) ss.close ();}}
It is important to note that TCP is a connection-oriented data transfer, so you need to start the server side before you open the client to successfully connect ....
In addition, I write the IP address as my actual network IP address, the occurrence of what data are not accepted. Change to 127.0.0.1 is no problem, to be solved.
Effect Show:
1) Start the service side
2) Start the client and send the data
3) server side, receipt after acceptance ...
References: Java video Bi Xiangdong presenter
Original address: http://blog.csdn.net/qingdujun/article/details/39322051
Java TCP uses sockets for network communication (3)