简体   繁体   中英

Java - How to keep a live socket connection

Ok guys im not that experienced so take it easy on me.

Ok so i have 2 programs, one for the server (my pc) and one for the client(other pcs) and this is the setup

server listens/accepts > client connects > server sends command to client > client executes.

and thats it, after that it disconnects BUT i need the client to stay connected so the server can keep sending commands as needed.

How can i achieve this?

I can provide more info if need just ask. thanks for all the help guys.

The server will receive a socket when accept() returns, and as long as that socket does not get closed then the connection remains open. The client will then run in a loop of read/execute-command until the server closes the connection. I can provide more details if needed.

There's a few official examples to get you started with Java sockets . Plus since its Java, getting this setup is pretty easy.

As Kevin already said, you'll open up a ServerSocket on some open port. Then call accept() which will return when a client connects with a Socket on the same port as the ServerSocket.

Also, make sure you pay attention to the specified host if you want the client program to connect from a computer different from the host. You might run into trouble with the loopback interface if you specify the host as "null" or "127.0.0.1".

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