简体   繁体   English

ServerSocket.accept()中的应用程序块

[英]Application blocks in ServerSocket.accept()

I'm trying to realize a simple client/server application in Java8. 我正在尝试在Java8中实现一个简单的客户端/服务器应用程序。 I'm using this code: 我正在使用此代码:

`package prova;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;



public class Main {
    public static void main(String args[]){
        ServerSocket ssock;
        try {
            System.out.println("Listening");
            ssock = new ServerSocket(8080);
            while(true){
                Socket sock;
                try {
                    sock = ssock.accept();
                    System.out.println("Connected");
                    new Thread(new Server(sock)).start();
                }catch(IOException e1){e1.printStackTrace();}
            }
        }catch(IOException e2){e2.printStackTrace();}
    }
}`

Server.java 服务器.java

package prova;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

public class Server implements Runnable{

    Socket clientSocket;

    public Server(Socket cSocket){
        this.clientSocket = cSocket;
    }

    public void run(){
         try {
             PrintStream pstream = new PrintStream
             (clientSocket.getOutputStream());
             for (int i = 100; i >= 0; i--) {
                pstream.println(i + 
                " bottles of beer on the wall");
             }
             pstream.close();
             clientSocket.close();
          }
          catch (IOException e) {
             System.out.println(e);
          }
    }

}

When the application arrives to execute the instruction ssock.accept(); 当应用程序到达执行指令ssock.accept();时。 the application crashes. 应用程序崩溃。 I really don't know what's the matter with this code. 我真的不知道这段代码有什么问题。 I've searched on internet but except for class server there is no difference between my code and a lot of solution/examples that i found. 我在互联网上进行搜索,但是除了类服务器之外,我的代码与我发现的许多解决方案/示例之间没有区别。 By the way since the application doesn't arrive to execute the thread I guess this is not related to my issue, maybe I'm wrong. 顺便说一下,由于应用程序尚未到达执行线程的位置,我想这与我的问题无关,也许我错了。 Thank you all in advance 谢谢大家

that's the strange fact it doesn't provide any stacktrace. 这是一个奇怪的事实,它不提供任何堆栈跟踪。 I'm running this code on win10 with eclipse mars 4.5.2. 我在带有eclipse mars 4.5.2的win10上运行此代码。 the code stops at this instruction sock = ssock.accept(); 代码在此指令处停止sock = ssock.accept();

Yes, it's supposed to stop there -- it's waiting for a client program to connect on that same socket, server socket 8080, that's what accept() does, but you don't do that anywhere. 是的,它应该就此停止-它正在等待客户端程序连接到同一套接字(服务器套接字8080)上,这就是accept()所做的,但是您不会在任何地方这样做。 The fix is simple -- have your client try to connect on the same socket that the server is waiting on. 修复很简单-让您的客户端尝试在服务器正在等待的同一套接字上进行连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM