Vous êtes ici

Very simple TCP socket server

A TCP socket server can be quite useful, when one has to test TCP connectivity between two computers. If server side computer runs Linux, it's really easy to start a TCP socket server: use the nc command. But when the computer runs Microsoft Windows, that's not that easy. One possible way is to use the Java code provided below. Copied from Sun's, sorry, Oracle's web site, it is slightly modified, in order to simplify it. It implements following functions:

  • accepts incoming TCP socket connection requests;
  • handles several connections;
  • each time a line (i.e. some characters followed by a carriage return) is received on one connection, it is echoed back to the sender;
  • when the line contains Bye, related connection is closed.

package com.monblocnotes.test.simpletcpserver;

import java.net.*;
import java.io.*;

public class SimpleTCPServer {
// Define server port here. private final static int PORT = 4444; public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; try { serverSocket = new ServerSocket(PORT); } catch (IOException e) { System.err.println("Could not listen on port " + PORT); System.exit(-1); } System.out.println("Waiting for client connections..."); while (listening) { Socket socket = null; socket = serverSocket.accept(); System.out.println("Client connection..."); new SimpleTCPServerThread(socket).start(); } serverSocket.close(); } }

package com.monblocnotes.test.simpletcpserver;

import java.net.*;
import java.io.*;

public class SimpleTCPServerThread extends Thread {
	private Socket socket = null;

	public SimpleTCPServerThread(Socket socket) {
		super("SimpleTCPServerThread");
		this.socket = socket;
	}

	public void run() {

		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(
					new InputStreamReader(
							socket.getInputStream()));

			String inputLine, outputLine;

			while ((inputLine = in.readLine()) != null) {
				outputLine = inputLine;
				out.println(outputLine);
				System.out.println("...echoed: " + inputLine);
				if (outputLine.equals("Bye")) {
					System.out.println("Closing connection...");
					break;
				}
			}
			out.close();
			in.close();
			socket.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}