socket server tutorial java code example

Example: Create a socket connection java

import java.io.*;
import java.net.*;

public class MyServer
{
  public static void main(String[] args)
  {
    try{
      //this line creates a server on port 1234
      ServerSocket server = new ServerSocket(1234);
      // this line accepts a connection from the client
  	  Socket serverSocket = server.accept();
      
      InputStream in = serverSocket.getInputStream();
      
      //You can do anything with the inputstream
      
    }catch(Exception e)
    {
      e.printStackTrace();
    }
  }
}

public class MyClient
{
  public static void main(String[] args)
  {
    try{
      // this line request a connection to the localhost server at port 1234
  	  Socket clientSocket = new Socket("localhost", 1234);
      
      OutputStream out = clientSocket.getOutputStream();
      //You can send anything to the server
    }catch(Exception e)
    {
      e.printStackTrace();
    }
  }
}

Tags:

Java Example