简体   繁体   English

一类的TCP客户端/服务器

[英]TCP Client/Server in one class

I am trying to write a program which is both a TCP client and a TCP server at the same time in order to broadcast messages across a distributed network. 我试图同时编写一个既是TCP客户端又是TCP服务器的程序,以便在分布式网络上广播消息。 After I was able to connect multiple instances of these programs together I discovered I was unable to read from the sockets. 在能够将这些程序的多个实例连接在一起之后,我发现无法从套接字读取信息。 I simplified the implementation, and still have the same problem. 我简化了实现,仍然有同样的问题。

The simplified code is as follows: 简化的代码如下:

public class Server {
public static void main(String[] args){
    try {
        ServerSocket ssocket = new ServerSocket(1234);
        Socket socket = new Socket("localhost", 1234);
        socket = ssocket.accept();

        String data = "Hello World";
        PrintWriter out;
        out = new PrintWriter(socket.getOutputStream(), true);
        System.out.print("Sending string: '" + data + "'\n");
        out.print(data);
        out.flush();

        BufferedReader in = new BufferedReader(new
                InputStreamReader(((Socket) socket).getInputStream()));
        System.out.print("Received string: '");

        while (!in.ready()) {}
        System.out.println(in.readLine());
        System.out.print("'\n...");
        in.close();
    } catch (UnknownHostException e2) {
        e2.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}
}

When running the code I receive the following output: 运行代码时,我收到以下输出:

Sending string: 'Hello World'
Received string: '

Why am I unable to read the input stream? 为什么我无法读取输入流?

The variable socket points to two different Socket objects, in turn: first, there's the one you create as a client to the server. 可变socket依次指向两个不同的Socket对象:首先,有一个您作为服务器客户端创建的对象。 Second, there's the one that the ServerSocket returns, which is connected to the client. 其次,有一个ServerSocket返回的值,该值已连接到客户端。 When you create the second one, you throw away your reference to the first one. 当您创建第二个时,您将放弃对第一个的引用。 But when you print data to one of the sockets, it's going to show up on the other one. 但是,当您将数据打印到其中一个插槽时,它将显示在另一个插槽上。 Since you only have a reference to one of the two sockets, you'll never be able to observe data being received. 由于您仅引用了两个套接字之一,因此您将永远无法观察到接收到的数据。

If you're going to to have a client and a server in the same process, talking to each other, you really need to use separate threads. 如果您要在同一进程中拥有一个客户端和一个服务器,并且彼此交谈,那么您确实需要使用单独的线程。 Typically in simple programs like this, the server part creates a new Thread in which to service each connection. 通常,在像这样的简单程序中,服务器部分会创建一个新的线程来为每个连接提供服务。 That would work well here. 在这里可以很好地工作。

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

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