27 May 2011 06:14 | java

This is my first attempt at network programming with Java.

In this case, the client and server are the same machine - my MacBook. However in theory it should work the same way when using two different machines.

My short-term plan is to get the client to send messages to the server, so that I can write something into the client, and the server can then display this message.

The next goal will be to make this go both ways - where two computers alternate between the role of Client and Server, sending messages to each other.

If you are a Java programmer looking for sample code, scroll down!

Simplified code

Use this to get started with setting up a TCP connection in Java. If you want to learn how to use networking for Java games, I'd suggest looking at UDP instead - it's less reliable and packets aren't necessary kept in the correct order, but it is faster.

// Connect to Socket
Socket sock = new Socket(SERVER_HOST, SERVER_PORT);
// ...
// When you are finished, remember to close the socket!

// Create the ServerSocket object
ServerSocket sock = new ServerSocket(SERVER_PORT);
// At the moment, we're just looping indefinitely, waiting for connections
while (true)
    // Listen for new sockets
    Socket newSock = sock.accept();
    // If a connection is found, deal with it in a separate thread
    // This allows us to continue listening on the current thread
    if (newSock != null)
        new MyThread(newSock).start();

Submit Feedback
Please rate this page based on the quality and helpfulness of the content to you.

Average 100% rating from 1 votes.

You may also be interested in…


Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +

12 May 2014 11:37

Post deleted by an administrator.

Included page "inc:signature" does not exist (create it now)

Edit | History (1) | Permalink

Add a new comment