服务器不监听请求

时间:2019-05-01 15:32:39

标签: java multithreading sockets

作为家庭作业的一部分,我必须建立两个类,一个是侦听器,另一个是向服务器发出请求(服务器已经由我的老师编写,我不知道代码的样子)。理论上:我连接到的服务器应以与我发送给他的请求完全相同的方式答复。但是实际上,我什么也得不到。

public class Listenerthread extends Thread {
    Socket s;
    Scanner answerServer;

    public Listenerthread(Socket socket) {
        this.s = socket;
        this.answerServer = new Scanner(new BufferedReader(new InputStreamReader(s.getInputStream())));
    }

    public void run() {
        System.out.println("Listening to the responses from the server......");
        while (true) {
            if (answerServer.hasNext()) {
                System.out.println(answerServer.nextLine());
            }
        }
    }
}
public class Mainthread {
    public static void main(String[] args) throws ParseException {
        Socket s = new Socket("someServer", 9999);
        Listenerthread server = new Listenerthread(s);
        server.start();
        if (s.isConnected()) {
            System.out.println("Connected");
        }
        String req = "Heyyy mate";  // server should sent me this back
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
        pw.println(req);
        pw.flush();
        //pw.close();
        //s.close(); 
    }
}

1 个答案:

答案 0 :(得分:0)

更新:在我开始编写此答案后,OP在问题上留下的评论表明,OP实际上不需要处理通信的服务器端。如果可能仍然有用,我将暂时保留该答案。


在使用客户端/服务器模型时,应该在服务器端使用ServerSocket,就像您在问题中提到的那样,但是似乎并未在代码中完成。

ServerSocket

这是一个ServerSocket的例子,可以解决这个问题。

ServerSocket serverSocket;

public void serverSocketTest()
{
    serverSocket = new ServerSocket(9999);
    // each of the below methods will happen on separate threads
    new Thread(this::serverSideAcceptConnectionFromClient).start();
    new Thread(this::clientSideConnectToServer).start();
}

public void clientSideConnectToServer()
{
    try {
        System.out.println("Client is trying to connect to server...");
        Socket connectionToServer = new Socket("localhost", 9999);
        OutputStream thisGoesToTheServer = connectionToServer.getOutputStream();
        InputStream thisIsDataComingFromServer = connectionToServer.getInputStream();
        System.out.println("Client successfully connected to server.");
    } catch(IOException ex) {
        System.out.println("Connection to server failed. (" + ex + ")");
    }
}

public void serverSideAcceptConnectionFromClient()
{
    try {
        System.out.println("Server is listening for potential clients...");
        Socket connectionFromClient = serverSocket.accept();
        InputStream thisIsDataComingFromClient = connectionFromClient.getInputStream();
        OutputStream thisIsGoesBackOutToClient = connectionFromClient.getOutputStream();
        System.out.println("Server accepted a client");
    } catch(IOException ex) {
        System.out.println("Error while listening for clients. (" + ex + ")");
    }
}