"Java" Java Socket Communication Demo sample

Source: Internet
Author: User
Tags sendmsg

Use socket (socket) to implement client and server communication.

Here are two examples:

The first is that each time a client sends a data, the server makes a response.

(That is, to take turns)

The other is that the client can continuously send data to the server, and the server can continuously send data to the client. Multithreaded


For convenience, the client server is placed on a single host. Open two processes respectively [haha, interprocess communication lol~]


PS: A prototype of a chat program

And the code is on GitHub: Https://github.com/MummyDing/socketChatDemo


Demo 1:

Simple socket communication. One sentence is over (always say add a loop)

Client

/**clientauthor:mummyding*/import java.lang.Runnable; Import java.io.*;        Import Java.net.*;class clientconnect{Socket client = null;           BufferedReader inputdata = null;        PrintWriter outputdata = null;        String Receivedata, SendData;              Clientconnect () {try {client = new Socket ("127.0.0.1", 5234);            DealData ();            } catch (Exception e) {System.out.println ("I Cann ' t connect!");        System.exit (1);    }} void DealData () {try{outputdata = new PrintWriter (Client.getoutputstream (), true);                Inputdata = new BufferedReader (New InputStreamReader (Client.getinputstream ()));  Sendmsg ();    Receivemsg ();    }catch (Exception e) {System.out.println ("Error ~");    }} void Sendmsg () {outputdata.println ("Hello Server");     } void Receivemsg () {try{receivedata = Inputdata.readline ();      SYSTEM.OUT.PRINTLN ("Server said" +receivedata); }catch (Exception E) {System.out.println ("Error");  }}}public class Client {public static void main (string[] args) {Clientconnect connecte = new Clientconnect (); }}


Service side:


/**serverauthor:mummyding*/import java.lang.Runnable; Import Java.net.*;import java.io.*;class serverconnect {serversocket serversocket = null; Socket clientsocket = null;        String Receivedata,senddata;serverconnect () {try {serversocket = new ServerSocket (5234);        Clientsocket = Serversocket.accept ();         DealData ();        } catch (Exception e) {System.out.println ("Server Bulid Error");        System.exit (1); }}void DealData () {Try{printwriter outputdata = new PrintWriter (Clientsocket.getoutputstream (), true); BufferedReader inputdata = new BufferedReader (New InputStreamReader (Clientsocket.getinputstream ())); ReceiveData =  Inputdata.readline ();  System.out.println ("Client say:" + receivedata); Outputdata.println ("Ha ha, I got your info:" +receivedata); }catch (Exception e) {System.out.println ("error!");}} public class Server{public static void Main (string[] args) {Serverconnect connecte = new Serverconnect ();}}


Demo 2:


On the basis of the demo 1, the progressive, realized a person can say a few words in a row. Multithreaded


Client

/**clientauthor:mummyding*/import Java.util.scanner;import java.lang.Runnable; Import java.io.*;        Import Java.net.*;class clientconnect{Socket client = null;           BufferedReader inputdata = null;        PrintWriter outputdata = null;        String Receivedata, SendData;              Clientconnect () {try {client = new Socket ("127.0.0.1", 5234);            DealData ();            Outputdata.println ("OK");            } catch (Exception e) {System.out.println ("I Cann ' t connecte!");        System.exit (0);    }} void DealData () {try{outputdata = new PrintWriter (Client.getoutputstream (), true);     Inputdata = new BufferedReader (New InputStreamReader (Client.getinputstream ()));                }catch (Exception e) {System.out.println ("Error ~");    System.exit (0);            }} String sendmsg () {Scanner sc = new Scanner (system.in);    SendData = Sc.nextline ();             Outputdata.println (SendData); OutputdatA.flush ();            System.out.println ("I say:" + senddata);    return senddata;             } Boolean receivemsg () {try{receivedata = Inputdata.readline ();    if (Receivedata.equals ("Shutdown")) return false;          SYSTEM.OUT.PRINTLN ("Server said" +receivedata);              }catch (Exception e) {System.out.println ("Error");        System.exit (0);    } return true; }}public class Client {public static void main (string[] args) {Clientconnect connect = new Clientconnect (); Thread t = new Thread (new Runnable () {public void run () {while (true) {Connect.deal                Data ();                    if (connect.receivemsg () = = False) {SYSTEM.OUT.PRINTLN ("SHUTDOWN!!!");                System.exit (0);       }                }            }        });        T.start (); while (Connect.sendmsg (). Equals ("shutdown") = = False) {} system.exit (0);}}



Service side:


/**serverauthor:mummyding*/import Java.util.scanner;import java.lang.Runnable; Import Java.net.*;import java.io.*;class serverconnect {serversocket serversocket = null; Socket clientsocket = null; String Receivedata,senddata; PrintWriter Outputdata;        BufferedReader Inputdata;serverconnect () {try {serversocket = new ServerSocket (5234);        Clientsocket = Serversocket.accept ();        } catch (Exception e) {System.out.println ("Server Bulid Error");        System.exit (1); }}void DealData () {try{outputdata = new PrintWriter (Clientsocket.getoutputstream (), true); inputdata = new Bufferedreade R (New InputStreamReader (Clientsocket.getinputstream ()));} catch (Exception e) {System.out.println ("error!"); System.exit (0);}} Boolean receivemsg () {try{receivedata = Inputdata.readline (); if (Receivedata.equals ("Shutdown")) return false; System.out.println ("Client say:" + receivedata);} catch (Exception e) {System.out.println ("Receive error~"); System.exit (0);} return true;} String sendmsg () {Scanner sc = new Scanner (system.in); senddata = Sc.nextline (); outputdata.println (SendData); Outputdata.flush (); System.out.println ("I say:" + senddata); return senddata;}} public class Server{public static void Main (string[] args) {Serverconnect connect = new Serverconnect (); Thread t = new Thread (new Runnable () {public void run () {while (true) {connect.dealdata (); if (connect.receivemsg () = = False)                    {SYSTEM.OUT.PRINTLN ("SHUTDOWN!!!");                System.exit (0); }}}); T.start (); while (Connect.sendmsg (). Equals ("shutdown") = = False) {}system.exit (0);}}


--------------------------------------------------

During the period of making a very two mistake, the client and the server used the "same name class", which led to the post-compilation of the "Class of the same name" covered out.

Complete code: Https://github.com/MummyDing/socketChatDemo
"Reprint Please specify the source"

Author: mummyding

Source: http://blog.csdn.net/mummyding/article/details/46445675



"Java" Java Socket Communication Demo sample

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.