Java 程序冻结直到建立套接字连接
我正在用 Java 从头开始做一个简单的 telnet 实现。 我已经在客户端和服务器之间建立了一个简单的套接字连接。我的问题是整个服务器应用程序在等待连接时冻结 - 即使我在单独的线程中运行它。有没有(最好是)简单的方法来解决这个问题?
线程起始片段:
worker slave = new worker();
Thread slaveThread = new Thread(slave);
slaveThread.run();
线程片段:
公共类工作者实现 Runnable{
public void run()
{
try
{
ServerSocket srv = new ServerSocket(1337);
System.out.println("Thread is running!");
Socket clientSocket = srv.accept();
System.out.println("Connection made.");
}catch (IOException e){
System.out.println("Failed.");
}
提前致谢!
Java新手
I am making a simple telnet implementation in Java from ground up.
I have already made a simple socket connection between client and server work. My problem is just that the whole server application freezes when it is waiting for a connection - even though i am running it in a seperate thread. Is there any (preferably) simple way to get around this?
Thread starter snippet:
worker slave = new worker();
Thread slaveThread = new Thread(slave);
slaveThread.run();
Thread snippet:
public class worker implements Runnable{
public void run()
{
try
{
ServerSocket srv = new ServerSocket(1337);
System.out.println("Thread is running!");
Socket clientSocket = srv.accept();
System.out.println("Connection made.");
}catch (IOException e){
System.out.println("Failed.");
}
Thanks in advance!
Java Newbie
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管 Thread 实现了 Runnable,但您不应该调用
run()
。您应该调用 Thread.start( ),它在新线程中调用run()
。如果您直接调用run()
,则当前线程是执行它的线程,而不是您创建的线程。Although Thread implements Runnable, you aren't supposed to call
run()
. You should call Thread.start(), which callsrun()
in the new thread. If you callrun()
directly, the current thread is the one that executes it, not the Thread you created.