026.3 Network Programming TCP Chat

Source: Internet
Author: User

Divided into the client and the service side, respectively to send and receive operations
##########################################################################
Client:
# # #思路:
1. Establish TCP Client Service
1.1 Because it is connection-oriented, there must be a connection to communicate
1.2 When creating a client, you must specify the destination address and port
2, once the connection is established, there is a channel to transmit data. can be transferred in the channel, this transmission is implemented through the stream, is the socket IO stream
3, get socket IO Write action can be sent to the server

# # #步骤:
1. Create socket object, clear destination IP and port
2. Get OutputStream object by Getoutstream method of socket object
3, write data through OutputStream object, achieve send
4. Close the Socket object

# # #代码: System.out.println ("client Start"); // 1. Create client object, clear destination and port New Socket ("192.168.10.141", 10000); // 2. Get the output stream in the socket stream and send the data to the server OutputStream out = s.getoutputstream (); // 3. Write data via output stream out.write ("I Miss You". GetBytes ()); // 4, close the resources s.close ();

####################################################################
Service side:
# # #思路:
1. Create a socket server-side service. The server listens on a port
2. Get the Client object
3. Gets the read stream of the client's socket stream
4. Display

# # #步骤:
1. Create a ServerSocket server object
2, through the ServerSocket object's accept method, gets the client socket object
3, through the client socket object Getinetaddress (). Gethostaddress () method gets the IP object and then gets the IP
4. Get the InputStream object through the getInputStream method of the client socket object
5. Obtain the data sent by the client through the Read method of the InputStream object.
6. Close the client socket object.

# # #代码: System.out.println (The server starts ... ");//1. Creating server-side ObjectsServerSocket SS =NewServerSocket (10003);//2. Get the Client objectSocket s =ss.accept (); String IP=s.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+ "... connect");//3. Get the read stream of the socket stream through the client objectInputStream in =S.getinputstream ();byte[] buf =New byte[1024];intLen =In.read (BUF); String Str=NewString (buf,0, Len); System.out.println (str); S.close ();

################################################################################
Simple and interactive TCP communication

/*# # # * Case two: To achieve the client and the service side of the transceiver process. * Client*/System.out.println ("Client 2 starts ...");//creates a client socket object. Specify the server address and port. Socket s =NewSocket ("192.168.1.223", 10004);//send data through the socket output stream to complete. OutputStream out =S.getoutputstream (); Out.write ("Service side, I'm coming.". GetBytes ());//reads the data returned by the server, through the socket input streamInputStream in =S.getinputstream ();byte[] buf =New byte[1024];intLen =In.read (BUF); String text=NewString (buf,0, Len); System.out.println (text);//close the resource. S.close ();

/*# # # * Case two: To achieve the client and the service side of the transceiver process. Server-side. */System.out.println ("Server 2 start ...");//Create a TCP server-side socket explicit port. ServerSocket SS =NewServerSocket (10004); while(true) {    //gets the client object. Socket s =ss.accept (); System.out.println (S.getinetaddress (). Gethostaddress ()+ "..... connected"); //read the data sent by the clientInputStream in =S.getinputstream (); byte[] buf =New byte[1024]; intLen =In.read (BUF); String text=NewString (buf, 0, Len);    System.out.println (text); //feedback data to the client. OutputStream out =S.getoutputstream (); Out.write ("Client, I have come to receive, oh yes! ". GetBytes ()); //shutting down the clients.close ();}//Close the service side. If you continue to get the client, you do not have to close the server. //ss.close ();

###########################################################################
I want to write a program that can send messages multiple times without finding what's wrong.

 Public classtcpserver2{ Public Static voidMain (string[] args)throwsIOException {serversocket ss=NewServerSocket (10005); Socket s=ss.accept (); serverreceive SR=Newserverreceive (s); Serversend Ssend=NewServersend (s); NewThread (SR). Start (); NewThread (ssend). Start (); }}classServersendImplementsrunnable{PrivateSocket S; PrivateOutputStream os;  PublicServersend (Socket s)throwsIOException {Super();  This. S =s; OS=S.getoutputstream (); } @Override Public voidrun () {BufferedReader br=NewBufferedReader (NewInputStreamReader (system.in)); String Line=NULL; Try {             while(line = Br.readline ())! =NULL) {os.write (Line.getbytes ()); if("//over". Equals (line)) {                     Break;        }} s.close (); } Catch(IOException e) {} }}classServerreceiveImplementsrunnable{PrivateSocket S; PrivateInputStream is;  PublicServerreceive (Socket s)throwsIOException {Super();  This. S =s; is=S.getinputstream (); } @Override Public voidrun () { while(true){            byte[] buf =New byte[1024]; Try {                intLen =Is.read (BUF); String Str=NewString (buf,0, Len); if("//over". Equals (str)) {                     Break;                } System.out.println (str);            S.close (); } Catch(IOException e) {} }}}
TCPServer
 Public classtcpclient2{ Public Static voidMain (string[] args)throwsunknownhostexception, IOException {Socket bothsocket=NewSocket ("127.0.0.1", 10005); Send2 Send=NewSend2 (Bothsocket); Receive2 Receive=NewReceive2 (Bothsocket); NewThread (send). Start (); NewThread (Receive). Start (); }}//create a send and receive class, use multi-threading, inherit the Runnable interface//Multi-threaded Send classclassSend2Implementsrunnable{PrivateSocket S;    OutputStream OS;  PublicSend2 (Socket s)throwsIOException {Super();  This, sb=s; OS=S.getoutputstream (); } @Override Public voidrun () {BufferedReader br=NewBufferedReader (NewInputStreamReader (system.in)); String Line=NULL; Try {             while(line = Br.readline ())! =NULL) {os.write (Line.getbytes ()); if("//over". Equals (line)) {                     Break;        }} s.close (); } Catch(IOException e) {} }}//multithreaded Receive classclassReceive2Implementsrunnable{PrivateSocket S; PrivateInputStream is;  PublicReceive2 (Socket s)throwsIOException {Super();  This. S =s; } @Override Public voidrun () { while(true){            byte[] buf =New byte[1024]; Try{ is=S.getinputstream (); intLen =Is.read (BUF); String Str=NewString (buf,0, Len); if("//over". Equals (str)) {                     Break;                } System.out.println (str);            S.close (); } Catch(IOException e) {} }}}
TCPClient

026.3 Network Programming TCP Chat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.