Socket and Socketserver Communication

Source: Internet
Author: User

Service-side code: Public classTalkserver { Public Static voidMain (String args[]) {Try {            //Create server, open 7777 portServerSocket Server =NewServerSocket (7777);  while(true) {Socket Socket=server.accept (); System.out.println ("Client-to-server connection established"); //Get Client MessagesBufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); String message=Br.readline (); System.out.println ("Client message:" +message);            Server.close (); }        } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

Client code:
 Public classtalkclient { Public Static voidMain (String args[]) {Try{Socket Socket=NewSocket ("127.0.0.1", 7777); BufferedWriter BW=NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); Scanner Scanner=NewScanner (system.in);  while(true) {System.out.println ("Please enter the message content:");                  Bw.write (Scanner.nextline ());                    Bw.flush ();                Socket.close ();            Scanner.close (); }        } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}
1, if there is no client service, directly through the browser to send the request, that is, input http://127.0.0.1:7777 or localhost:7777, the server operation results:
The client and the server have established a connection
Client message: get/http/1.1
2, socket create client send request, through keyboard input send request
Client Run Results:
Please enter the message content to send:
Hello
Server Run Results:
The client and the server have established a connection
Client message: Hello

Socket and Socketserver Communication

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.