java 聊天服务器_带有命令的Java聊天服务器

当我开始网络时,我遇到了同样的问题。您的线程在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()希望这有帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值