Build a network server in Java language, realize communication between client and server, realize client has independent thread, do not interfere with each other

Source: Internet
Author: User

Server:

1. Communication with clients is mostly the way I/O streams

2. The docking method is socket socket, socket through IP address and port number to establish the connection

3. (points that once had a great impact on understanding) all information about the output stream emitted by the server becomes the input stream for the client, and all output streams for all clients are included in the server's input stream.

(That is, even if the socket is connected, the input-output stream is relative to itself, sending out its own internal information all with the output stream, accepting external data all using the input stream!) )

The code implementation of the simple server:

 Public Static voidmain (String [] args) {Try {
Set up the local server and listen for the 6788 port number ServerSocket servers=NewServerSocket (6788); Get keyboard input as information sent by the server to the client
Scanner Reader=NewScanner (system.in); while(true) {Socket C=server.accept (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (C.getinputstream ())); BufferedWriter BW=NewBufferedWriter (NewOutputStreamWriter (C.getoutputstream ())); String Line; if((Line=br.readline ())! =NULL) {System.out.println (line); } if((Line=reader.nextline ())! =NULL) {bw.write (line); Bw.newline ();//due to the judgment of the time are nextline (), so each input must be given a newline bw.flush (); } } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }}

Client-side code implementations that link to and communicate with the server:

 Public Static voidMain (string[] args) {Try {
6788 Port connected to localhost (127.0.0.1 is local host IP) Socket c=NewSocket ("127.0.0.1", 6788); Get keyboard input information as information sent to the server Scanner reader=NewScanner (system.in); BufferedReader BR=NewBufferedReader (NewInputStreamReader (C.getinputstream ())); BufferedWriter BW=NewBufferedWriter (NewOutputStreamWriter (C.getoutputstream ())); String Line; while(true){ if(line = Reader.nextline ())! =NULL) {bw.write (line);  Bw.newline (); Client and server read operations are rows, so you need to give a newline, to avoid error bw.flush (); } if((Line=br.readline ())! =NULL) {System.out.println (line); } } } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }

It is impossible for a general server to serve only one client, and when there are many clients, it is necessary to establish a separate thread for each client link, so that the client does not interfere and run independently.

There are two ways to implement threading control:

1. The custom thread class inherits the thread and reproduces the run () method;

2. Customize a common class to implement the Runnable interface (this method is used to realize multithreading control)

Specific code implementation:

//server's code
Public Static voidMain (string[] args) {Try{serversocket ServerSocket=NewServerSocket (6666); while(true) {
Always monitor if there is a client connection to the Socket s=serversocket.accept (); Each client opens a separate thread to execute thread ch whenever there is a client connection=NewThread (NewThreadmanager (s)); Ch.start (); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }

To implement a custom class for a thread:

 Public classThreadmanagerImplementsrunnable{Privatesocket socket;  PublicThreadmanager (Socket s) { This. Socket =s; } @Override Public voidrun () {BufferedWriter bw;        BufferedReader BR; Try{BW=NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); BR=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); Continuously send a signal to the client, the number is constantly changing, if the client has linked, send the information independent thread implementation
for (int i = 0; i<1000000;i++) {
Bw.write (i+ "" "" "" "" ");
Bw.newline ();
Bw.flush ();
} } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}

Client-side code implementations to receive the server:

 Public Static voidMain (string[] args) {Try {
Link to local 6666-Port Socket s=NewSocket ("127.0.0.1", 6666 ); BufferedReader BR=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); BufferedWriter BW=NewBufferedWriter (NewOutputStreamWriter (S.getoutputstream ())); String Line; while(true){ while(line = Br.readline ())! =NULL) {//The information sent by the server is output
System.out.println (line); } } } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }

Note: For the convenience of observation, you can start the client code in the CMD window, repeatedly open a few dos windows, and link to the local port 6666, you will receive the server sent over the increment number, all DOS windows are started, you can find that each window of the number of growth is not the same, but have been running , non-interference, to this point, for the client-created independent thread implementation.

Note: There are a lot of network knowledge has not been collected and collated, when you see here again, remember to complement the basic part, to re-tamp the foundation, strengthen memories.

Build a network server in Java language, realize communication between client and server, realize client has independent thread, do not interfere with each other

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.