其他服务器套接字在向服务器套接字发送数据时接收数据。

huangapple 未分类评论56阅读模式
英文:

Other server sockets receive data when sending data to the server sockets

问题

首先,我很抱歉我的英语能力。

我正在尝试使用多线程来连接与客户端的套接字。

我的服务器线程独立地运行为多线程,
我为每个客户端使用不同的套接字端口号,以防万一。

然而,当我连接一个客户端时,如果另一个客户端已经连接,
来自初始客户端的数据会被发送到后连接的客户端的服务器套接字。

例如:
客户端1定期向其自己的服务器套接字发送数据。
但是当连接客户端2时,客户端2的服务器套接字接收到那些数据,而不是客户端1的服务器套接字。

这是服务器线程的代码。

public class serverthread extends Thread {
	int  num;
	static Socket socket;
	static InputStream in;
	static DataInputStream dis;

	public serverthread(Socket s, int num) {
		this.socket = s;
		this.num = num;
		try {
			in = socket.getInputStream();
			dis = new DataInputStream(in);
		} catch (IOException e) {
			log.loglist.add("1exit(interect) : " + socket.getInetAddress());
		}
	}

	public void run() {
		try {
			while (true) {
				int come = dis.readInt();
			}
		} catch (IOException e) {
			server.endsocket(num);
		}
	}
}

在我看来,套接字显然是不同的,但数据却被发送到错误的套接字。这是应该这样吗?还是我的编码有问题?

英文:

First of all, I'm sorry about my English ability.

I'm trying to use multi-thread to connect socket with clients.

My server threads operate separately as multi-threads
and I make different in socket port number each client just in case.

However when I connect a client when another client is already connected,
data from the initial client is sent to late client's server socket.

For example:
client1 send data to its own server socket periodically.
however when client2 is connected, client2's server socket take that data instead of client1's server socket.

Here's the server thread code.

public class serverthread extends Thread {
	int  num;
	static Socket socket;
	static InputStream in;
	static DataInputStream dis;

	public serverthread(Socket s, int num) {
		this.socket = s;
		this.num = num;
		try {
			in = socket.getInputStream();
			dis = new DataInputStream(in);
		} catch (IOException e) {
			log.loglist.add("1exit(interect) : " + socket.getInetAddress());
		}
	}

	public void run() {
		try {
			while (true) {
				int come = dis.readInt();
			}
		} catch (IOException e) {
			server.endsocket(num);
		}
	}
}

It seems to me that it's obvious that the socket is different, but it's sending data to the wrong socket.
Is it supposed to be like this? Or am I coding wrong?

huangapple
  • 本文由 发表于 2020年7月28日 23:18:33
  • 转载请务必保留本文链接:https://java.coder-hub.com/63137511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定