Step by step test and improve the socket communication graphic solution in Java (3)

Source: Internet
Author: User
Tags connect socket

Directory

Introduction

Socket Communication in Java

Single-threaded one-to-one server 1 --> 1 client

Single-threaded one-to-one server 1 <--> 1 client

Multi-thread one-to-multiple Server 1 <--> N client [non-chatting room server sends data through user input]

Multithreading one-to-multiple Server 1 <--> N client [chat room]

Multi-threaded final server and client integration [Swing program]

[Multithreading] One-to-multiple Server 1 <--> N client (non-Chatting Room servers send data through user input)Yes, the solution is to send data and receive data in different processes. In this way, these two processes do not affect each other. The solution is as follows:

Of course, if you want to consider the following, when multiple clients connect to the same server, you should enable a thread for each sockt connection. However, for the client, you only need to separate sending and receiving. Therefore, in the client, you can put the sent data and the master process together. For example:

The Code is as follows:
Package com17.tcp; import Java. io. ioexception; import java.net. serversocket; import java.net. socket; public class myserver {public static void main (string [] ARGs) {try {serversocket Ss = new serversocket (30000); While (true) {// This line of code will block, will always wait for other people to connect socket S = ss. accept (); If (S. isconnected () {system. out. println ("a client connects to this server" + S. getinetaddress ();} // every time the client connects, start a serverthread to serve the client new thread (New serverthread (s )). start (); // send data to the client new thread (New serverthread2 (s )). start () ;}} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace ();}}}

Threads that accept and print data:
Package com17.tcp; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printstream; import java.net. socket; import Java. util. optional; public class serverthread implements runnable {// defines the Socket socket s processed by the current thread = NULL; // The input stream bufferedreader BR = NULL for the socket processed by the thread; public serverthread (socket s) {try {This. S = s; // The input stream BR = new bufferedreader (n EW inputstreamreader (S. getinputstream ();} catch (ioexception e) {e. printstacktrace () ;}@ override public void run () {try {string content = NULL; // The while (content = readfromclient () data sent from the client is continuously read from the socket in a loop ())! = NULL) {system. out. println ("Message from client:" + content);} system. out. println ("message:" + content); printstream PS = new printstream (S. getoutputstream (); PS. println (BR. readline ();} catch (exception e) {try {S. close ();} catch (ioexception ex) {ex. printstacktrace () ;}}// defines the method for reading client data. Private string readfromclient () {try {return BR. readline ();} // if an exception is caught, the client corresponding to the socket has disabled catch (ioexception e) {e. printstacktrace ();} return NULL ;}}

The thread that sends data to the client:
Package com17.tcp; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printstream; import java.net. socket; public class serverthread2 implements runnable {private socket s; // Private printstream PS used to process sent data = NULL; Public serverthread2 (socket s) {try {This. S = s; PS = new printstream (S. getoutputstream ();} catch (ioexception e) {try {S. close ();} c Atch (ioexception ex) {ex. printstacktrace () ;}}@ override public void run () {try {// send data to the client string line = NULL; // read the input of the keyboard continuously. bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); While (line = BR. readline ())! = NULL) {// write the user's keyboard input content to the output stream pS corresponding to the socket. println (line) ;}} catch (ioexception e) {e. printstacktrace ();}}}

Client:
Package com17.tcp; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printstream; import java.net. socket; // reads users' keyboard input, write the data entered by the user to the output stream corresponding to the socket // read the data in the input stream corresponding to the socket (the data sent from the server) // and print the data out. Myclient is responsible for reading user keyboard input, that is, the main thread of the program. Public class myclient {public static void main (string [] ARGs) {try {socket S = new socket ("127.0.0.1", 30000 ); // The client starts clientthread to continuously read data from the server in the county. New thread (New clientthread (s )). start (); // obtain the output stream printstream PS = new printstream (S. getoutputstream (); string line = NULL; // read the input of the keyboard continuously; bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); While (line = BR. readline ())! = NULL) {// write the user's keyboard input content to the output stream pS corresponding to the socket. println (line) ;}} catch (ioexception e) {e. printstacktrace ();}}}
Client thread:

Package com17.tcp; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import java.net. socket; public class clientthread implements runnable {// socketprivate socket s to be processed by this thread; // The input stream bufferedreader BR = NULL for the socket processed by this thread; public clientthread (socket s) throws ioexception {This. S = s; BR = new bufferedreader (New inputstreamreader (S. getinputstream ();} @ overridepublic void Run () {try {string content = NULL; // constantly read the content in the socket input stream and print the output content while (content = Br. Readline ())! = NULL) {system. Out. println ("Message from server:" + content) ;}} catch (ioexception e) {e. printstacktrace ();}}}
The effect is as follows:

However, through the above Code, we need to implement the following:

Although multithreading is used in the above Code, each client request will generate a read thread and write thread. However, the requirements cannot be met. Why? It mainly lies in the writing thread. Although the writing thread captures the Socket socket for sending, the writing thread listens to the user input system. In at all times. In this way, when multiple clients connect to the server, multiple threads on the server listen to the user input system. In. However, the server has only one DOS window, instead of listening to a user input system. In in a DOS window on the client. The server access result is as follows:

Therefore, it is not feasible for the server to send data to multiple clients in the form of user input. Code can always be sent to active threads. The result is not what you think. It is sent to the thread you think. Of course, if the server does not listen for user input, the above requirements can be fulfilled. Let's change the server side: Do not listen for user input. On the server side, when the receiving thread receives the customer's data, it sends the data. Server, thread

The demo above modified in the acceptance thread
// The while (content = readfromclient () data sent from the client is continuously read from the socket in a loop ())! = NULL) {system. out. println ("Message from client:" + content); PS. println ("client" + S. getinetaddress () + "the message has been received, and the message is:" + content );}

As follows: [Multithreading] One-to-multiple Server 1 <--> N client (Chat Room)

I want to use the above examples to understand the communication methods and understand the communication principles and methods. Let's talk about the chat room communication, which is similar to our QQ group. If one person expresses his opinion, others can see the message. I guess the QQ implementation method is to forward through the server [this is my opinion]. The implementation method of this example is as follows:

In this example, the code is not pasted. Let's talk about the idea. There is a list on the server side, which is used to save the socket of the client. As long as the client connects to the server, it adds the socket of the client to the server list. When any client data is received, the data is forwarded to any client socket in the list. Some code is as follows:
// The while (content = readfromclient () data sent from the client is continuously read from the socket in a loop ())! = NULL) {// each socket in the socketlist // sends the read content to each socket once for (socket S: myserver. socketlist) {printstream PS = new printstream (S. getoutputstream (); PS. println (content );}}

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.