Java Socket Application (vii)-Multi-client communication using multithreading

Source: Internet
Author: User

Reprint Please specify : Http://blog.csdn.net/uniquewonderq

Problem: One server can communicate with multiple clients

Basic steps:

1. Server-Side Create ServerSocket method, loop call Accept () method waits for client to connect

2. Client creates a request connection for sockets and services

3. The service side accepts the client's request, establishes the leased line connection

4. Connect the two sockets dialog on a separate thread

5. Server side continues to wait for new connections

Create a server-related thread class:

Package Com.test;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstream;import Java.io.inputstreamreader;import java.io.outputstream;import Java.io.printwriter;import java.net.Socket;/* * Server threading Classes */public class Serverthread extends Thread {//and Socketsocket socket associated with this thread = Null;public serverthread (socket Socke T) {this.socket = socket;} A thread performs an operation that responds to the client's request public void run () {InputStream is=null;inputstreamreader isr=null; BufferedReader Br=null;outputstream Os=null; PrintWriter pw=null;try {//Gets the input stream and reads the client information is = Socket.getinputstream (); ISR = new InputStreamReader (is); br = new BufferedReader (ISR); String Info=null;while ((Info=br.readline ())!=null) {//iterates over the client's information System.out.println ("I am the server, the client says" +info);} Socket.shutdowninput ();//Close input stream//Get output stream, respond to client request OS = Socket.getoutputstream ();p w = new PrintWriter (OS);p w.write ("Welcome! ");p W.flush ();//Call Flush () method to buffer output} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{//Close Resource try {if (pw!=null) pw.close (); if (OS!=null) Os.close (); if (br!=null) br.close (); if (isr!=null) isr.close (); if (is!=null) is.close (); if (socket!=null) Socket.close ();} catch (IOException e) {e.printstacktrace ();}}}}


2. Server-side

Package Com.test;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.printwriter;import java.net.InetAddress; Import Java.net.serversocket;import java.net.socket;/* * Socket communication based on TCP protocol for user login * Server-side */public Class Server {public STA tic void Main (string[] args) {try {//1. Create a server-side socket, that is, ServerSocket, specify the bound port, and listen for this port ServerSocket serversocket=new ServerSocket (8888); Socket socket=null;//Record the number of clients int count=0; SYSTEM.OUT.PRINTLN ("* * * server is about to start, waiting for client Connection");//loop listener waits for the client to connect while (TRUE) {//calls the Accept () method to start listening, waiting for the client to connect socket= Serversocket.accept ();//Create a new thread Serverthread serverthread=new serverthread (socket);//Start thread serverthread.start (); The number of count++;//statistics clients System.out.println ("Number of clients:" +count); inetaddress address=socket.getinetaddress (); System.out.println ("IP of the current client:" +address.gethostaddress ());}} catch (IOException e) {e.printstacktrace ();}}}



3. Client clients

Package Com.test;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.printwriter;import Java.net.Socket;import Java.util.logging.level;import java.util.logging.logger;/** * * @author WONDERQ */public class Client {//Client public STA tic void Main (string[] args) {try {//1. Create client socket, specify server address and port number socket socket=new socket ("12            7.0.0.1 ", 8888); 2. Gets the output stream used to send information to the server OutputStream os=socket.getoutputstream ();//Byte output stream//convert to print stream Prin              Twriter pw=new printwriter (OS);              Pw.write ("User name: Wonderq; Password: root");              Pw.flush ();//flush cache, output information to server//close output stream socket.shutdownoutput ();              3. Get the input stream to read the server-side response information InputStream is=socket.getinputstream ();              BufferedReader br=new BufferedReader (New InputStreamReader (IS));           String Info=null; while ((Info=br.readline ())!=null) {System.out.println ("I am the client, the server side returns information is:" +info);              }//4. Close resource Br.close ();              Is.close ();              Pw.close ();              Os.close ();        Socket.close ();        } catch (IOException ex) {Logger.getlogger (Client.class.getName ()). log (Level.severe, NULL, ex); }    }}

Run the server-side output first:

* * * server is about to start, waiting for client connections * * *


Then run the client:


Then check the server side:



Change the output information of the client, Pw.write ("Username: User; Password: admin");

And then start a client. After starting the client output information is unchanged, the service side information changes as follows:



It can be explained that the server side is constantly looping through the connections of new clients.

Because it's all local, all IPs are 127.0.0.1. If it is true, then it will be quite different.






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Socket Application (vii)-Multi-client communication using multithreading

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.