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:
[Java]View Plaincopyprint?
- Package TCP.CLINET.QDJ;
- Import Java.io.OutputStream;
- Import Java.net.Socket;
- Client of TCP Communication
- 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 Resources
- S.close ();
- }
- }
Service side, the code is as follows:
[Java]View Plaincopyprint?
- Package TCP.SERVER.QDJ;
- Import Java.io.InputStream;
- Import Java.net.ServerSocket;
- Import Java.net.Socket;
- Service side of TCP communication
- Public class Cserver {
- public static void Main (string[] args) throws exception{
- //Set up the server socket service and listen to a port.
- ServerSocket ss = New ServerSocket (6877);
- //Get the client object from the link through the Accept method
- SYSTEM.OUT.PRINTLN ("Server is started, listening on port 6876, waiting for data ...");
- Socket s = ss.accept ();
- //Get an 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 the service side (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)