-
-
Save mashhurs/84cdbf774f54613339802bb561393c6e to your computer and use it in GitHub Desktop.
Java TCP server
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
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