Skip to content

Instantly share code, notes, and snippets.

@DrBrad
Created January 18, 2018 00:09
Show Gist options
  • Save DrBrad/6e971bdc2520625e61da41680433d451 to your computer and use it in GitHub Desktop.
Save DrBrad/6e971bdc2520625e61da41680433d451 to your computer and use it in GitHub Desktop.
Simple how2 Sockets Server & Client Java
//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