简体   繁体   中英

Application blocks in ServerSocket.accept()

I'm trying to realize a simple client/server application in 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

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(); 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. the code stops at this instruction 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. The fix is simple -- have your client try to connect on the same socket that the server is waiting on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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