Created
January 18, 2018 00:09
-
-
Save DrBrad/6e971bdc2520625e61da41680433d451 to your computer and use it in GitHub Desktop.
Simple how2 Sockets Server & Client Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SERVER | |
public static void main(String args[]){ | |
new Thread(new Runnable(){ | |
@Override | |
public void run(){ | |
try{ | |
ServerSocket serverSocket = new ServerSocket(2020); | |
Socket socket; | |
while((socket = serverSocket.accept()) != null){ | |
startSocket(socket); | |
} | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
}).start(); | |
} | |
public static void startSocket(Socket socket){ | |
try{ | |
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); | |
out.println("pong"); | |
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); | |
System.out.println(in.readLine()); | |
out.flush(); | |
out.close(); | |
in.close(); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
}finally{ | |
try{ | |
socket.close(); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
//CLIENT | |
public static void main(String args[]){ | |
new Thread(new Runnable(){ | |
@Override | |
public void run(){ | |
try{ | |
Socket socket = new Socket("127.0.0.1",2020); | |
startSocket(socket); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
}).start(); | |
} | |
public static void startSocket(Socket socket){ | |
try{ | |
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); | |
out.println("ping"); | |
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); | |
System.out.println(in.readLine()); | |
out.flush(); | |
out.close(); | |
in.close(); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
}finally{ | |
try{ | |
socket.close(); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment