Java--socket

Source: Internet
Author: User

Refer to the online example, wrote a socket communication example, the operation can be successful

1. Create two normal Java project, directly map the following


2. The client code is as follows

Package Client;import Java.io.outputstreamwriter;import Java.io.writer;import java.net.socket;public class Client { public static void Main (String args[]) {try{//creates the client socket socket SOCKET = new Socket ("127.0.0.1", 9999);// Writes the output stream from the socket writer = new OutputStreamWriter (Socket.getoutputstream ()); Writer.write ("Hello World");// Refresh output stream Writer.flush (); Writer.close (); Socket.close ();} catch (Exception e) {e.printstacktrace ();}}}

3. Server-side code is as follows

package server;import java.io.inputstreamreader;import java.io.reader;import  java.net.serversocket;import java.net.socket;public class server {public static  Void main (string args[]) {try {//Create a serversocket to listen for client requests on port number 9999 Serversocket serversocket  = new serversocket (9999); Socket socket = serversocket.accept ();//Gets the input stream from the socket reader reader = new  InputStreamReader (Socket.getinputstream ());char chars[] = new char[1024];int len; Stringbuilder builder = new stringbuilder ();while  (Len = reader.read (chars )  != -1)  {builder.append (new string (Chars, 0, len));} System.out.println ("receive from client message=: "  + builder); Reader.close (); Socket.close (); Serversocket.close ();}  catch  (exception e)  {// todo: handle exceptione.prinTstacktrace ();}}} 

4. Run As server-side code, let the server run, and then run the client code, the results are as follows


Receive from client message=: Hello world.


Java--socket

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.