java--Network Programming

Source: Internet
Author: User

1.Client Terminal

Importjava.net.* ;ImportJava.io.* ; Public classClient { Public Static voidMain (string[] args)throwsException {Socket s=NewSocket ("localhost", 8888); //send a message to the serverInputStreamReader r =NewInputStreamReader (system.in); BufferedReader BR=NewBufferedReader (R); System.out.println ("Input your want to write:" ); String msg=Br.readline (); OutputStream OS=S.getoutputstream (); DataOutputStream DS=Newdataoutputstream (OS);                Ds.writeutf (msg); //accept messages from the serverInputStream R1 =S.getinputstream (); DataInputStream Dis=NewDataInputStream (R1); String servermsg=Dis.readutf (); System.out.println ("Reverse the Server massage is:" +servermsg);        Br.close ();    S.close (); }}

2.Server Terminal

1 Importjava.net.*;2 ImportJava.io.* ;3 4  Public classServer {5      Public Static voidMain (string[] args)throwsException {6ServerSocket ServerSocket =NewServerSocket (8888);7          while(true) {8             9             //Accept Client MessagesTenSocket socket =serversocket.accept (); OneSYSTEM.OUT.PRINTLN ("A client connect this server!")); AInputStream r =Socket.getinputstream (); -          -DataInputStream dis =NewDataInputStream (r); theString clientmsg =Dis.readutf (); -System.out.println ("Send to this server:" +clientmsg); -              -             //reply message to client +BufferedReader input =NewBufferedReader ( -                 NewInputStreamReader (system.in) +             ); AString backmsg =input.readline (); atOutputStream OS =Socket.getoutputstream (); -DataOutputStream dos =Newdataoutputstream (OS); - Dos.writeutf (backmsg); - input.close (); -         } -     } in}

The above code enables point-to-point communication.

java--Network Programming

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.