简体   繁体   English

Java客户端/服务器套接字问题

[英]Java client/server socket issue

I'm learning Java socket programming, and I'm pretty positive my code is correct, but for some reason the server and the client don't communicate. 我正在学习Java套接字编程,我非常肯定我的代码是正确的,但是由于某些原因服务器和客户端无法通信。 I'm not quite sure if they're even connecting. 我不太确定他们是否还在连接。 Here is what I've done so far. 到目前为止,这是我所做的。

Server: 服务器:

public static void main(String[] args) throws Exception
{
    Main_Server server = new Main_Server();
    server.run();
}

public void run() throws Exception
{
    ServerSocket server = new ServerSocket(444); //Port
    Socket sSocket = server.accept();

    BufferedReader bfr = new BufferedReader(new InputStreamReader(sSocket.getInputStream()));

    String clientMessage = bfr.readLine();
    System.out.println("Client: "+clientMessage);

    if (clientMessage != null)
    {
        PrintStream ps = new PrintStream(sSocket.getOutputStream());
        ps.println("Message Received.");
    }
}

Client: 客户:

public static void main(String[] args) throws Exception
{
    Client_One client = new Client_One();
    client.run();
}

public void run() throws Exception
{
    Socket clientSocket = new Socket("localhost", 444);

    PrintStream ps = new PrintStream(clientSocket.getOutputStream());
    ps.println("Hello, server.");

    BufferedReader bfr = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String serverMessage = bfr.readLine();
    System.out.println("Server: "+serverMessage);
}

So I run the server first and the client after (I'm currently using NetBeans IDE 8.1). 因此,我先运行服务器,然后再运行客户端(我目前正在使用NetBeans IDE 8.1)。 The programs run and just sit there, but nothing happens after that. 程序运行并就在那儿,但此后没有任何反应。 Why is this? 为什么是这样? I just have two empty consoles. 我只有两个空的控制台。 Thank you for your time. 感谢您的时间。

If you use a Buffer you need to flush it or close it, otherwise if the buffer is not full the data remains in the buffer. 如果使用缓冲区,则需要flushclose它,否则,如果缓冲区未满,数据将保留在缓冲区中。 It is ok also to close it because as you can see from the javadoc closing a stream will also flush it. 也可以关闭它,因为从javadoc中可以看到,关闭流也会刷新它。

From the javadoc of OutputStream you can see what flushing means: 从OutputStream的javadoc中 ,您可以看到刷新的含义:

Flushes this output stream and forces any buffered output bytes to be written out . 刷新此输出流并强制将所有缓冲的输出字节写出

Note: additionally remember to close both input and output streams when you finished to use them, otherwise you still have not properly closed resources using memory. 注意:另外请记住,在完成使用完输入和输出流后,请同时关闭它们,否则您仍无法使用内存正确关闭资源。

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

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