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
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值