Created
October 21, 2018 20:43
-
-
Save a11ce/432fe099094c83e0b7a6f35f244fc8f0 to your computer and use it in GitHub Desktop.
Multithreaded Java server boilerplate
This file contains hidden or 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.util.Scanner; | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
public class PortsEasy | |
{ | |
static int PORTNUM = 6012; | |
public static void main(String[] args) throws IOException | |
{ | |
int clientTally = 0; | |
ServerSocket listener = new ServerSocket(PORTNUM); | |
System.out.println("Server up on port " + PORTNUM); | |
try | |
{ | |
while(true) | |
{ | |
new Client(listener.accept(),clientTally++).start(); | |
} | |
} | |
finally | |
{ | |
listener.close(); | |
} | |
} | |
private static class Client extends Thread | |
{ | |
private Socket socket; | |
private int clientNumber; | |
public Client(Socket s, int c) | |
{ | |
this.socket = s; | |
this.clientNumber = c; | |
} | |
public void run() | |
{ | |
try | |
{ | |
System.out.println("Client " + clientNumber + " (" + socket.getRemoteSocketAddress() + ") connected"); | |
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); | |
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); | |
//code here | |
out.println("hello"); | |
//code here | |
socket.close(); | |
} | |
catch (Exception E) | |
{ | |
System.out.println("Error with client " + clientNumber + ": " + E); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment