Java教程

java中给出一个多线程TCP的ServerSocket例子?

本文主要是介绍java中给出一个多线程TCP的ServerSocket例子?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

以下的例子,是一个服务器对多个客户端。我们的客户端程序可以运行很多遍,代表多个客户。

/*in this frame work, many clients can access the server with many thread and many socket using only one port,
bbb client use bbb socket with bbb thread, by default, one port can accept 50 socket. */


import java.net.ServerSocket;
import java.io.*;
import java.net.Socket;

public class ThreadServers {

public static void main(String[] args) {
try {
/* public ServerSocket(int port)
throws IOExceptionCreates a server socket, bound to the specified port.
The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication
arrives when the queue is full, the connection is refused.


public ServerSocket(int port,int backlog)
throws IOException Creates a server socket and binds it to the specified local port number, with the specified backlog.
The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection
indication arrives when the queue is full, the connection is refused.

*/
ServerSocket ss = new ServerSocket(8089);
for(;;){
/* here this ServerSocket can accept unlimited client socket.every time after
it accept one, it just come back from the loop, and block here on accept statement.
a new client corresponds to a new socket */
Socket s = ss.accept();
/* this reader get data from socket, then print in the console.
a new client corresponds to a new thread */
ReadThread reader = new ReadThread(s);
// WriteThread writer = new WriteThread(s);

/* WriteThread get the input from console, then write it to the network. */
reader.start();
/*in this case, we have to comment out the following statement because if there
are two clients, if we type in characters in the console, which clients do we
type in to send out to? so the example is made easier not to server to send
out, to make it work, you can make the server to pop up two windows, then one window
corresponds to one client, in window, if you type in some characters, you send them to this client. */
// writer.start();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}

}

 

更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44639795/article/details/102474344

这篇关于java中给出一个多线程TCP的ServerSocket例子?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!