Skip to content

Instantly share code, notes, and snippets.

@mashhurs
Created August 18, 2022 18:47
Show Gist options
  • Save mashhurs/84cdbf774f54613339802bb561393c6e to your computer and use it in GitHub Desktop.
Save mashhurs/84cdbf774f54613339802bb561393c6e to your computer and use it in GitHub Desktop.
Java TCP server
import java.net.*;
import java.io.*;
public class TcpServer {
public static void main(String[] args) {
final int port = args.length >= 1 ? Integer.parseInt(args[0]) : 9000;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
String text = "";
int readSize = 1024;
char[] buffer = new char[readSize];
do {
int readCharsSize = reader.read(buffer, 0, readSize);
if (readCharsSize > 0) {
System.out.println("Number of chars read: " + readCharsSize);
}
} while (!text.equals("bye"));
socket.close();
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment