简体   繁体   中英

TCP socket programing and multithreading in java

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?

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

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.

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