create a socket connection java

Solutions on MaxInterview for create a socket connection java by the best coders in the world

showing results for - "create a socket connection java"
Lina
29 Jul 2017
1import java.io.*;
2import java.net.*;
3
4public class MyServer
5{
6  public static void main(String[] args)
7  {
8    try{
9      //this line creates a server on port 1234
10      ServerSocket server = new ServerSocket(1234);
11      // this line accepts a connection from the client
12  	  Socket serverSocket = server.accept();
13      
14      InputStream in = serverSocket.getInputStream();
15      
16      //You can do anything with the inputstream
17      
18    }catch(Exception e)
19    {
20      e.printStackTrace();
21    }
22  }
23}
24
25public class MyClient
26{
27  public static void main(String[] args)
28  {
29    try{
30      // this line request a connection to the localhost server at port 1234
31  	  Socket clientSocket = new Socket("localhost", 1234);
32      
33      OutputStream out = clientSocket.getOutputStream();
34      //You can send anything to the server
35    }catch(Exception e)
36    {
37      e.printStackTrace();
38    }
39  }
40}