12 March 2017

Java | Client & Server | Simple Socket Programming

To make an application that can communicate with other applications like chat-app or multiplayer games, we need a server that serve data between clients. A Client send data to the server and the server send it to another client. Server and client send data to each other via sockets.
How to create a Server
  • Create a class with a main method
  • Create an instance of ServerSocket. You need to pass any port number as a parameter ServerSocket ss = new ServerSocket(9999);
  • In order to accept an incoming client connection, we have to call the ServerSocket.accept() method. As soon as connection request is made from client, this method will return a socket that created specifically for this client.
  • To send and receive data from client, you can use OutputStreamWriter and BufferedReader
  • The Server
How to create a Client
  • Create a class with a main method
  • Create an instance of Socket class and pass the port number and the private ip address of your server as parameter.  You can use localhost instead of ip for local testing. Socket s = new Socket(ip, port);
  • To send and receive data from client, you can use OutputStreamWriter and BufferedReader
  • The Client
How it works
Run the server. once the accept() method is called, the server will wait for a client to connect. When you run the client, a connection request is made and ServerSocket will then create a socket that is connected to the client's socket until Socket.close() method is called. To make a simple chat application, put a Writer and a Reader in a while loop and use a Scanner to take user input.

No comments:

Post a Comment