Skip to content

Instantly share code, notes, and snippets.

@muddokon
Created September 6, 2019 00:43
Show Gist options
  • Save muddokon/3c74f6d5a1a925aaba0adf3f9e769fbb to your computer and use it in GitHub Desktop.
Save muddokon/3c74f6d5a1a925aaba0adf3f9e769fbb to your computer and use it in GitHub Desktop.
TCPServer.java
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main (String args[]) {
try{
int serverPort = 7896; // the server port
ServerSocket listenSocket = new ServerSocket(serverPort);
while(true) {
Socket clientSocket = listenSocket.accept();
Connection c = new Connection(clientSocket);
}
} catch(IOException e) {System.out.println("Listen socket:"+e.getMessage());}
}
}
class Connection extends Thread {
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection (Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new DataInputStream( clientSocket.getInputStream());
out =new DataOutputStream( clientSocket.getOutputStream());
this.start();
} catch(IOException e) {System.out.println("Connection:"+e.getMessage());}
}
public void run(){
try { // an echo server
String data = in.readUTF(); // read a line of data from the stream
out.writeUTF(data);
}catch (EOFException e){System.out.println("EOF:"+e.getMessage());
} catch(IOException e) {System.out.println("readline:"+e.getMessage());
} finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}}
}
}
//Code by Coulouris et al
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment