gpt4 book ai didi

Java serversocket 控件同步问题

转载 作者:行者123 更新时间:2023-12-04 05:13:38 26 4
gpt4 key购买 nike

我正在使用一些 java 创建一个小客户端来监控网络。对于网络上的每个节点,我运行一个客户端,但也运行一个 ServerSocket 来监听传入的连接。我写的代码似乎卡在了 ServerSocket.listen() 方法上。我正在尝试运行一些需要启动服务器套接字的测试代码,并在设置后向其发送一些数据。基本上我的问题是这样的:

客户端.java

/*snip*/
public void listen(){
try{
ServerSocket server = new ServerSocket(1234);
server.listen();
Socket client = server.accept()
System.out.println("got connection");
... do stuff
catch(IOException ex){
ex.printStackTrace();
}
}

测试客户端
/*snip*/
Client client = new Client();
client.listen();
System.out.println("client constructed, waiting for connection");
Socket sock = new Socket("localhost", 1234);
... do stuff

java ServerSocket 的每个其他示例都将它放在自己的类中,只是为了循环自身并在无限循环中运行。如果可能的话,我试图让服务器从另一个主要方法执行。据我所知,问题是 client.listen() 方法永远不会完成,因为套接字永远不会获得它的连接。我尝试在 TestClient 中执行该行代码后建立连接:在 eclipse 中, println 都不会打印到输出中。有没有另一种方法来编写控制结构来巧妙地处理这个问题?

最佳答案

也许你正在寻找这样的东西?您可以让服务器套接字在单独的线程中运行

package test;

import java.net.*;

public class Clerver {

private ServerSocket serverSocket;
private int listenPort;
private Thread listenerThread;

public Clerver(int listenPort) {
this.listenPort = listenPort;
}

public void runIt() throws Exception {

this.serverSocket = new ServerSocket(listenPort);
this.listenerThread = new Thread() {
public void run() {
synchronized (Clerver.this) {
Clerver.this.notify();
}
try {
Socket clientSocket = Clerver.this.serverSocket.accept();
receiveDataOnServer(clientSocket);
clientSocket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
this.listenerThread.start();
synchronized (this) {
this.wait();
}
Socket sock = new Socket("localhost", listenPort);
sendDataFromClient(sock);
receiveDataFromServer(sock);
System.out.println(">> All done!");
listenerThread.join();
System.out.println(">> Bye Bye!");
}

private void sendDataFromClient(Socket sock) throws Exception {
sock.getOutputStream().write("Hello".getBytes());
System.out.println(">> Sent HELLO");
}

private void receiveDataFromServer(Socket sock) throws Exception {
byte[] buf = new byte[1024];
int bread = sock.getInputStream().read(buf);
String response = new String(buf, 0, bread);
System.out.println("<< RESPONSE from SERVER: " + response);
}

private void receiveDataOnServer(Socket sock) throws Exception {

byte[] buf = new byte[1024];
int bread = sock.getInputStream().read(buf);
String response = new String(buf, 0, bread);
System.out.println(">> Received on Server : " + response);
sock.getOutputStream().write("WORLD".getBytes());
System.out.println(">> SERVER sent response back");
}

/**
* @param args
*/
public static void main(String[] args) throws Exception {
Clerver c = new Clerver(1234);
c.runIt();

}

}

关于Java serversocket 控件同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14570372/

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