当我开始网络时,我遇到了同样的问题。您的线程在ss.accept()处停止,然后在代码中不继续。您需要实现专用于ServerSocket的另一个Thread。这是一个例子:
public class Server implements Runnable
{
ServerSocket server; // the serverSock your clients will connect to
Thread thread; // the thread for your server
boolean running; // whether or not the server is running
public Server(int port)
{
running = false; // server is not yet running
connect(port); // setup server
}
public void connect(int port)
{
try
{
server = new ServerSocket(port); setup server on port
running = true; // server is running
thread = new Thread(this); // initialize server thread
thread.start(); // start thread
} catch(Exception e){e.printStackTrace(); running = false;} // port is in use
}
public void disconnect()
{
try
{
server.close();
}catch(Exception e){e.printStackTrace();}
running = false;
thread = null;
server = null;
}
public void run()
{
while(running)
{
Socket client = server.accept(); // client connects to server
// handle the client...
ClientHandler handler = new ClientHandler(client);
}
}
public class ClientHandler implements Runnable
{
Thread clientThread;
DataOutputStream out;
public ClientHandler(Socket socket)
{
out = new DataOutputStream(socket.getOutputStream());//setup the output stream
clientThread = new Thread(this); // setup the new thread
clientThread.start(); // start the thread
}
public void run()
{
/* this is where you get your input from the console and then
* send the output to the client
*/
}
}
}这应该让你的主线程不会卡在server.accept()希望这有帮助!