Skip to content

Instantly share code, notes, and snippets.

@kamilbolka
Created February 5, 2019 15:17
Show Gist options
  • Save kamilbolka/d11b5f1581b76752f1257a6314841acd to your computer and use it in GitHub Desktop.
Save kamilbolka/d11b5f1581b76752f1257a6314841acd to your computer and use it in GitHub Desktop.
import java.io.*;
import java.net.*;
/**
*
* @author kamilbolka
*/
public class ServerSocketMachine {
private static final int PORT = 6666;
/**
* Start the socket server
* @param args
*/
public static void main(String[] args) {
new ServerSocketMachine(PORT);
}
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader input;
private PrintWriter output;
public ServerSocketMachine(int port) {
try {
// Print out the status IP address
System.out.println("======= Address =======");
InetAddress ip = InetAddress.getLocalHost();
System.out.println("Local host name" + ip.getHostName());
System.out.println("Local host Address: " + ip.getHostAddress());
// Create the server socket
serverSocket = new ServerSocket(port, 100, ip);
System.out.println("Server is starting... on ip: " + serverSocket.getInetAddress().getHostAddress());
// Wait for the request from the client
socket = serverSocket.accept();
System.out.println("Server has connected with clinet!");
// Create stream links between server and the new client
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream());
String line = "";
while (line.equalsIgnoreCase("quit") == false) {
// Read client input
line = input.readLine();
System.out.println("Clinet said: " + line);
}
// Shutdown the server
System.out.println("Server is shutting down...");
serverSocket.close();
socket.close();
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment