gpt4 book ai didi

Java 多线程 TCP 套接字 - 从客户端接收消息,直到它们断开连接

转载 作者:可可西里 更新时间:2023-11-01 02:51:08 26 4
gpt4 key购买 nike

我有以下代码可以从我的 Java 服务器接受多个客户端。

private class SocketServerThread extends Thread {
int count = 0;
String error_message = null;
@Override
public void run() {
try{
serverSocket = new ServerSocket(theSocketServerPORT);
while (true){
final Socket socket = serverSocket.accept();
count++;
runOnUiThread(new Runnable(){
@Override
public void run() {
Toast.makeText(getApplicationContext(),"New Client with IP: " + socket.getInetAddress() + " and PORT: " + socket.getPort(),Toast.LENGTH_LONG).show();
}
});
SocketServerListenToMessage socketServerListenToMessage = new SocketServerListenToMessage(socket);
socketServerListenToMessage.run();// Start to Receive now
}
}catch (IOException e){
Log.e("IO ERROR",e.toString());
error_message = "IO ERROR";
}catch (Exception e){

Log.e("EX ERROR",e.toString());
error_message = "EX ERROR";
}
if(error_message!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),error_message,Toast.LENGTH_LONG).show();
}
});
}
}
}

客户端连接后,我调用SocketServerListenToMessage 开始监听客户端消息。

以下代码用于SocketServerListenToMessage

private class SocketServerListenToMessage extends Thread{
Socket theClientSocket;
SocketServerListenToMessage(Socket clientSocketListener){
theClientSocket = clientSocketListener;
Log.w("SERVER STATUS","Starting to Listen to Clients...");
}
@Override
public void run(){
try{
InputStream is = theClientSocket.getInputStream();
while(true){
byte[] lenBytes = new byte[4];
is.read(lenBytes, 0, 4);
int len = (((lenBytes[3] & 0xff) << 24) | ((lenBytes[2] & 0xff) << 16) |
((lenBytes[1] & 0xff) << 8) | (lenBytes[0] & 0xff));
byte[] receivedBytes = new byte[len];
is.read(receivedBytes, 0, len);
final String received = new String(receivedBytes, 0, len);

runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Client Says: " + received, Toast.LENGTH_LONG).show();
Log.w("Client Says", received);
}
});
}
}catch (IOException e){
Log.e("IO ERR FROM LISTEN MSG", e.toString());
}
catch (Exception e){
Log.e("EX ERR FROM LISTEN MSG", e.toString());
}
}
}

通过上面的代码,我可以连接多个客户端。我还可以从我的客户端接收 Message。但问题是我只能从连接到我的服务器的 第一个客户端 接收消息。 第二个很快 客户端不是。

下面的代码用于我的客户端发送消息。请注意,我正在为我的客户端使用 C#

IPEndPoint serverAddress;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //I am using Socket

/*********To Send Message to Server**********/

String toSend = txt_v.Text; //The message came from TextBox.
Task f = Task.Factory.StartNew(() => {
if (clientSocket.Connected)
{
int toSendLen = System.Text.Encoding.ASCII.GetByteCount(toSend);
byte[] toSendBytes = System.Text.Encoding.ASCII.GetBytes(toSend);
byte[] toSendLenBytes = System.BitConverter.GetBytes(toSendLen);
clientSocket.Send(toSendLenBytes);
clientSocket.Send(toSendBytes);

}
});

我认为问题出在SocketServerListenToMessage 中的while 循环 中。我试图删除 while 循环 并且服务器能够从所有客户端接收消息,但每个客户端只有一条消息。我希望服务器在断开连接之前收听客户端的消息。我该怎么做?

最佳答案

我只是让它发挥作用。感谢这个Link .

如果我没记错的话,来自 link ,我使用的是单线程。所以从我的 SocketServerThread 我必须改变

SocketServerListenToMessage socketServerListenToMessage = new SocketServerListenToMessage(socket); 
socketServerListenToMessage.run();// Start to Receive now

new Thread(new SocketServerListenToMessage(socket)).start();

并将类 SocketServerListenToMessage 更改为

private class SocketServerListenToMessage implements Runnable {
protected Socket clientSocket = null;

public SocketServerListenToMessage(Socket clientSocket) {
this.clientSocket = clientSocket;
}

@Override
public void run() {
try {
while (true){
InputStream is = clientSocket.getInputStream();
byte[] lenBytes = new byte[4];
is.read(lenBytes, 0, 4);
int len = (((lenBytes[3] & 0xff) << 24) | ((lenBytes[2] & 0xff) << 16) |
((lenBytes[1] & 0xff) << 8) | (lenBytes[0] & 0xff));
byte[] receivedBytes = new byte[len];
is.read(receivedBytes, 0, len);
final String received = new String(receivedBytes, 0, len);

runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Client Says: " + received, Toast.LENGTH_LONG).show();
Log.w("Client Says", received);

}
});
}

} catch (IOException e) {
Log.e("IO ERR FROM LISTEN MSG", e.toString());
} catch (Exception e) {
Log.e("EX ERR FROM LISTEN MSG", e.toString());
} finally {
try{
clientSocket.close();
Log.w("CLIENT DISCONNECTED", "A client is disconnected.");
}catch (IOException e){
Log.w("IO ERR DISCONNECTION", e.toString());
}
}
}
}

我只需要 implement Runnable 而不是 Thread 使其成为 Multi

关于Java 多线程 TCP 套接字 - 从客户端接收消息,直到它们断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com