[Java] Java Socket Communication Example, using ocket

Source: Internet
Author: User

[Java] Java Socket Communication Example, using ocket

Use socket to implement communication between the client and the server.

Here are two examples:

The first is that each time the client sends a data, the server responds. (That is, sending in turn)

The second is that the client can send data continuously to the server, or the server can send data continuously to the client. (Multithreading)


For convenience, the client server is deployed on one host and two processes are opened separately [Haha, communication between processes lol ~]


PS: prototype of a chat program

Code is also on GitHub: https://github.com/MummyDing/socketChatDemo


Demo 1:

For simple Socket communication, one sentence is over (just keep adding 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();  }}


Server:


/**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:


This step is performed on the basis of Demo 1, so that one person can continue to say a few words. (Multithreading)


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.dealData();                if(connect.receiveMsg() == false){                    System.out.println("SHUTDOWN!!!");                    System.exit(0);                }                }            }        });       t.start();        while(connect.sendMsg().equals("shutdown") == false){         }        System.exit(0);}}



Server:


/**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 BufferedReader(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);}}


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

A second mistake was made during this period. The client and server used the "same name class", which caused later compilation to overwrite the previous "Same Name class.

[Reprinted with the source]

Author: MummyDing

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



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.