简体   繁体   English

简单的客户端服务器通信

[英]Simple Client Server communication

I am learning currently about client server communication using Java through sockets. 我目前正在学习有关通过套接字使用Java的客户端服务器通信的信息。 First of all I retrieve my own machine's IP Address using following code. 首先,我使用以下代码检索自己机器的IP地址。

InetAddress ownIP=InetAddress.getLocalHost();
//the result being 192.168.56.1

Now I write the simple client server application using the above mentioned address as follow 现在,我使用上述地址编写简单的客户端服务器应用程序,如下所示

public class SimpleClientServer {
public static void main(String[] args)
{
    //sending "Hello World" to the server
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try
    {

        clientSocket = new Socket("192.168.56.1", 16000);

        out = new PrintWriter(clientSocket.getOutputStream(), true);

        in = new BufferedReader(new InputStreamReader(
                                                 clientSocket.getInputStream()));

        out.println("Hello World");

        out.close();
        in.close();
        clientSocket.close();
    }
    catch(IOException e)
    {
        System.err.println("Error occured " + e);

    }
}
}

The result hower reads a follow. 结果咆哮读取跟随。

Error occured java.net.ConnectException: Connection refused: connect

What is the reason for this. 这是什么原因。 Is it just the wrong host address? 只是错误的主机地址吗?

From the code you have given you seem to suggest that there is currently nothing listening on port 16000 for the socket to connect to. 从给出的代码中,您似乎暗示当前没有任何监听端口16000的套接字连接。

If this is the case you need to implement something like 如果是这种情况,您需要实施类似

ServerSocket serverSocket = null;
try {
    serverSocket = new ServerSocket(16000);
}
catch (IOException e) {
    System.err.println("Could not listen on port: 16000.");
    System.exit(1);
}

More information can be found in the Java online documentation and a full example is included. 可以在Java在线文档中找到更多信息,并包括完整的示例

With sockets, no matter what language you're using, you either initiate a connection with socket_connect or you listen and accept with socket_listen and socket_accept. 使用套接字,无论使用哪种语言,都可以通过socket_connect发起连接,或者通过socket_listen和socket_accept进行监听和接受。 Your socket_connect call is trying to connect to an ip address that doesn't seem to be listening to anything. 您的socket_connect调用正在尝试连接到似乎没有监听任何内容的IP地址。

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

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