Demo entry 6685401

87898

   

Submitted by anonymous on Dec 19, 2017 at 21:52
Language: Java. Code size: 1.4 kB.

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

public class MultiThreadedEchoServer {
	public static void main(String[] args) throws IOException {
		try {
			int port = 7777;
			System.out.println("Starting hello server port " + port);
			ServerSocket serverSocket = new ServerSocket(port);
			System.out.println("Waiting...");
			while (true) {
				Socket clientConnection = serverSocket.accept();
				System.out.println("Accepted from " + clientConnection.getInetAddress());
				Thread t = new CommunicationThread(clientConnection);
				t.start();
			}
		} catch (IOException e) {
			System.err.println("Error");
			System.exit(1);
		}

	}

	public static class CommunicationThread extends Thread {
		Socket clientSocket;

		public CommunicationThread(Socket s) {
			clientSocket = s;
		}

		public void run() {
			PrintWriter out;
			try {
				out = new PrintWriter(clientSocket.getOutputStream(), true);
				BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				String inputLine;
				while ((inputLine = in.readLine()) != null) {
					System.out.println("Server: " + inputLine);
					out.println(inputLine);
					if (inputLine.equals("Bye."))
						break;
				}
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).