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?

1
  • 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. Commented Dec 14, 2015 at 16:38

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

since data are taken from a keyboard, the speed of your single-threaded solution should be sufficient.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.