前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java中给出一个多线程TCP的ServerSocket例子?

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

作者头像
马克java社区
修改2021-05-11 10:05:13
5270
修改2021-05-11 10:05:13
举报
文章被收录于专栏:java大数据

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

/*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 afte

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

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档