[Tutorial] [Part 2] How to make a TCP server. | Sololearn: Learn to code for FREE!


[Tutorial] [Part 2] How to make a TCP server.

This is part two of my tutorial. Please read part one first! Server: int port = 1234; ServerSocket welcomeSocket = new ServerSocket(port); This is going to start the server, and produce an error if a server already is running on this port. Now that the server have been successfully started, you want it to be able to accept a new client! Socket potentialUser = welcomeSocket.accept(); This command will halt the thread, make it unresponsive as it waits for a client to connect. Therefore its always good practise to do this on a seperate thread, if you have a UI (User Interface). This will produce an error if the server is shutdown. Client: String IP = ""; int port = 1234; Socket socket = new Socket(IP, port); This command creates a new socket variable, which will try to connect to the IP with the port. Remember to suround it with a try catch, as it will produce an error if no server is found. Now that your client have successfully connected to the server, what now? The next step for the server is to put the client in a seperate thread from the server, and wait for messages from the client to handle. The client will do the same, but from the server instead. The server should now proceed to wait for another client to connect, so basicly wrap it up in a loop. What you are able to do now is connect more clients, and you can exchange messages between them. If you want the code for sending messages and retrieving them, search up TCP in the code section. There is a fully working example there as mentioned earlier. I might expand this article if people request. If you have any questions, want to add something or saw anything wrong, go ahead and comment! Also, I would appreciate a like if you found this article useful! ~ Frekvens1

7/24/2016 10:26:17 PM

Thomas Alme

4 Answers

New Answer


You can find the complete code in the code section by searching for TCP. *EDIT: Code playground *EDIT: https://code.sololearn.com/csaVDjS8N8O2/?ref=app


great tutorial.


can I get the complete code


code section?