Socket communication for Java Network Programming (II)

Source: Internet
Author: User

Prior to the previous introduction of some basic principles of socket communication, and how to let the client and the server to establish communication, and to implement some basic steps of communication (including first make the server-side connection with the client, after establishing a connection, the server side began to listen to the client's request, after hearing the client's request, Through the input and output stream processing the relevant information to achieve communication, the end of communication completed a series of communication and so on.

But before just a single client to communicate with the server, and our actual application in the case of a single client is almost nonexistent, are multiple clients at the same time interacting with the server (here at the same time the interaction will have concurrency problems, for concurrency is not very understanding of the problem, only know that the concept), That requires the server to listen to the client's request (written in the while loop, and the condition is always true, the dead loop), each time a client's request is heard, it is necessary to create a socket to establish communication with it (through the thread implementation, whenever a client's request is heard, The service side has to open a separate thread to communicate with it).


The following code is directly affixed to it:


1, the server socket, (this inside through the cycle of death to allow the servers to continuously listen to the request from the client)

It is important to note that the server must be started before the client because it will be started before it can listen for client requests


Package Com.socket;import java.io.ioexception;import Java.net.serversocket;import java.net.socket;/** * server-side Socket * @ Author Feizi * @time 2014-11-14 pm 5:08:16 */public class Serversocketmany {/** * main test method * @param args * @throws ioexcepti On */public static void main (string[] args) throws Ioexception{system.out.println ("server is started, waiting for client connections ....");// Create a server-side socket, ServerSocket, waiting for client requests ServerSocket Server = new ServerSocket (5555); int count = 0;//number of clients to hear socket Socket = null;//Server-side socket//dead loop, let the service side loop listen while (true) {///////Service side start listening Client connection socket = Server.accept ();//start thread, communicate with client thread Serverthread = new Serverthread (socket); Serverthread.start ();//count, Statistics client connection number count++; System.out.println ("The number of clients currently linked is:" +count+ ");}}}


2, the server-side thread implementation class, the main thread is to implement communication with the client (through the input and output stream to receive and respond to data information)


Package Com.socket;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;/** * Create a service thread, loop through requests from clients, multiple clients * @author Feizi * @time 2014-11-14 pm 5:36:45 */public class Serverthread extends thread{//whenever you hear A new client, the server side will have a socket to communicate with it public socket socket = null;//Default construction method, leave the public serverthread () {}//with the parameter construction method public Serverthread (socket socket) {this.socket = socket;} Overwrite the Run method public void run () {//Gets the input byte stream inputstream in = null;//wraps the input stream into the input character stream InputStreamReader ISR = null;// Add buffer for character input stream BufferedReader br = null;//After receiving information, response information to client, get output byte stream outputstream out = null;//wrap byte output stream into character print output stream PrintWriter PW = null;try {in = Socket.getinputstream (), ISR = new InputStreamReader (in), br = new BufferedReader (ISR),//read data from character input stream string data = Null;while ((data = Br.readline ()) = null) {System.out.println ("I am the server, the client says" +data);} Call the shutdown method to close the socket input stream socket.shutdowninput (); out = Socket.getoUtputstream ();p w = new PrintWriter (out);p w.write ("username and password correct");p W.flush ();/ Call the shutdown method to close the socket output stream socket.shutdownoutput ();} catch (IOException e) {e.printstacktrace ();} finally{//Close Resource try {if (null! = PW) pw.close (); if (null! = out) out.close (); if (null! = BR) br.close (); if (null! = ISR) Isr.close (); if (null! = IN) in.close (); if (null! = socket) socket.close ();} catch (IOException e) {e.printstacktrace ();}}}}



3, the client socket, this and the single-client case, in the first article is described in detail


Package Com.socket;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.net.unknownhostexception;/** * Client Socket * @author Feizi * @time 2014-11-14 pm 5:18:06 */public class Clientsocketdemo {/** * Main test method * @param args * @throws unknownhostexception * @throws ioexception */public static void Main (string[] Arg s) throws Unknownhostexception, ioexception{//create client socket, request to server//string address = "127.0.0.1"; String address = "localhost";//server addresses int port = 5555;//port number Socket socket = new socket (address, port);//Get socket byte output stream outputs Stream out = Socket.getoutputstream ();//wraps the byte output stream into a character print output stream PrintWriter pw = new PrintWriter (out);//pw.print ("Username: admin, Password: 123 ");//pw.print (" User name: Tom, Password: 456 ");//pw.print (" User name: Dark, Password: 789 ");//pw.print (" Username: white, Password: 111 ");p W.print (" User name: Green, Password: 222 ");//Refresh Output stream Pw.flush ();//Call shutdown method to close the output stream of the socket Socket.shutdownoutput ();//Receive ServiceThe input stream InputStream in = Socket.getinputstream ();//wraps the byte input stream into a character input stream InputStreamReader ISR = new InputStreamReader (in);//Add buffer for the character input stream BufferedReader br = new BufferedReader (ISR);//Read data in the input stream of the character string = Null;while (data = Br.readline ()) = null) {System.out.println ("I am the client, server says:" +data);} Call the shutdown method to close the input stream of the socket Socket.shutdowninput (); Br.close (); Isr.close (); In.close ();p w.close (); Out.close (); Socket.close ();}}


Here is the result of the program running:


Client:




Server-side:




You can click this link to see the single-client interaction with the server:

Socket communication for Java Network Programming (i)


Grow a little every day, always believe: tiandaochouqin, efforts, struggle, all cut possible!

Socket communication for Java Network Programming (II)

Related Article

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.