1

I want to send and receive data between three computers using a TCP socket in Java

  • The first computer takes the data from the keyboard and sends it to the second computer.
  • The second computer takes the data from the first and sends it to the third computer.

My question is: Can I implement the TCP socket program in the second computer (which receives data from the first computer and sends it to the third at the same time) without using multithreading?

cslotty
  • 1,696
  • 20
  • 28
MA.H
  • 11
  • 2
  • 1
    the default/simplest socket support in java is using the "blocking" IO APIs, which require multiple threads to use correctly. The "non-blocking" APIs can be done single threaded, but are _much more complex_ to use. – jtahlborn Dec 14 '15 at 16:38

2 Answers2

1

Yes you can. (but it's probably stupid)

Just bind a port and listen on it on server 2. Server 1 connects to server 2 and sends data. Server 2 reads data, connects to server 3 and sends him data, on same thread.

Without multithreading, you can either read input from server 1 either send data to server 3. Moreover, you can handle data from server 1 only one by one. The program will work slowly (no faster as it can be with multithreading).

Prim
  • 2,880
  • 2
  • 15
  • 29
0

You should make machine 2 as server which will listen on some fixed ip:port. Make machine 1 and 3 as client which will connect to machine 2 on fixed ip:port.

Regarding multithreading, you can make your server thread less by using poll/select. Please refer to link Is there epoll equivalent in Java? which explains poll/select better.

Community
  • 1
  • 1
Ritesh
  • 1,809
  • 1
  • 14
  • 16