-
-
Save seyedsahil/18e6a920172d16d0dcf3004ee5a84de1 to your computer and use it in GitHub Desktop.
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
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.PrintWriter; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.List; | |
/** | |
* @author Seyed Sahil | |
*/ | |
public class App { | |
public static void main(String[] args) throws IOException, InterruptedException { | |
ServerSocket serverSocket = new ServerSocket(8080); | |
System.out.println("Server session started at " + new Date()); | |
int connections = 0; | |
List<Thread> connectionThreads = new ArrayList<>(); | |
while (connections != 2) { | |
System.out.println("Server is listening on port 8080"); | |
Socket clientSocket = serverSocket.accept(); | |
connections++; | |
System.out.println("Server connected with Client-" + connections + " at " + new Date()); | |
final int clientId = connections; | |
Thread connectionThread = new Thread(() -> { | |
try { | |
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); | |
out.println("Hello Client-" + clientId + ", What is your name ?"); | |
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | |
out.println("Hey " + in.readLine() + ", Nice to meet you!"); | |
in.close(); | |
out.close(); | |
clientSocket.close(); | |
} catch (IOException exception) { | |
exception.printStackTrace(); | |
} | |
}); | |
connectionThread.start(); | |
connectionThreads.add(connectionThread); | |
} | |
for (Thread connectionThread : connectionThreads) { | |
connectionThread.join(); | |
} | |
serverSocket.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment