我有一个客户端和一个服务器。客户端在特定端口上绑定一个套接字,服务器向客户端发送回一个新端口,客户端应该在新端口号上绑定一个新套接字。
从主服务器线程开始,我启动一个线程,一旦服务器准备好并正在侦听新端口,就会向客户端发送消息,以便客户端可以尝试连接到新端口。来自子线程的管道没有将消息发送到客户端。所以客户端和服务器都只是冻结,这似乎是一个死锁,但我不确定。客户端这行代码:System.out.println("FROM SERVER:" + inMsg_rport); 没有执行。
服务器代码:
class server
{
public static void main(String argv[]) throws Exception
{
String newPort;
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(5555);
clientSocket = serverSocket.accept();
DataOutputStream serverOut =
new DataOutputStream(clientSocket.getOutputStream());
int r_port = 5556;
Thread appThread = new Thread(new serverApp(serverOut, r_port));
appThread.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
static class serverApp implements Runnable
{
DataOutputStream serverOut;
int nPort;
public serverApp(DataOutputStream servO, int r_port)
{
this.serverOut = servO;
this.nPort = r_port;
}
@Override
public void run()
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(nPort);
serverOut.writeBytes(sr_port);
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
}
客户端代码:
class client {
public static void main(String argv[]) throws Exception
{
String serverIp = argv[0];
String msg = argv[2];
int port = Integer.parseInt(argv[1]);
Socket clientSocket = new Socket(InetAddress.getByName(serverIp), port);
BufferedReader clientIn =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inMsg_rport = clientIn.readLine();
System.out.println("FROM SERVER: " + inMsg_rport);
int r_port = Integer.parseInt(inMsg_rport);
clientSocket.close();
System.out.println("Closed connection");
Socket new_clientSocket = new Socket(InetAddress.getByName(serverIp), r_port);
}
}