简体   繁体   中英

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. 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. Second, there's the one that the ServerSocket returns, which is connected to the client. 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.

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