Last active
December 26, 2015 10:59
-
-
Save fado/7140863 to your computer and use it in GitHub Desktop.
New multithreaded implementation of the EchoServer
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
package uk.ac.qub.networking; | |
import java.io.*; | |
import java.net.*; | |
public class NewEchoServer { | |
public static void main(String[] args) { | |
int port = 12321; | |
NewEchoServer server = new NewEchoServer( port ); | |
server.startServer(); | |
} | |
ServerSocket newEchoServer = null; | |
Socket clientSocket = null; | |
int numConnections = 0; | |
int port; | |
public NewEchoServer( int port ) { | |
this.port = port; | |
} | |
public void startServer() { | |
try { | |
newEchoServer = new ServerSocket(port); | |
} | |
catch (IOException e) { | |
System.out.println(e); | |
} | |
System.out.println("Server started. Waiting for connections."); | |
while ( true ) { | |
try { | |
clientSocket = newEchoServer.accept(); | |
numConnections++; | |
newEchoServerConnection connection = new newEchoServerConnection ( | |
clientSocket, numConnections, this); | |
new Thread(connection).start(); | |
} | |
catch (IOException e) { | |
System.out.println(e); | |
} | |
} | |
} | |
} | |
class newEchoServerConnection implements Runnable { | |
BufferedReader input; | |
PrintStream output; | |
Socket clientSocket; | |
int id; | |
NewEchoServer server; | |
public newEchoServerConnection(Socket clientSocket, int id, NewEchoServer server) { | |
this.clientSocket = clientSocket; | |
this.id = id; | |
this.server = server; | |
System.out.println("Connection "+ id +" established with : " | |
+ clientSocket); | |
try { | |
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | |
output = new PrintStream(clientSocket.getOutputStream()); | |
} catch (IOException e) { | |
System.out.println(e); | |
} | |
} | |
public void run() { | |
String line; | |
try { | |
while(true) { | |
line = input.readLine(); | |
System.out.println( "Received: "+ line + " from connection "+ id + "."); | |
output.println("SERVER> "+ line); | |
System.out.println( "Sent: "+ line + " to client "+ id + "."); | |
} | |
} catch (IOException e) { | |
System.out.println(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment