Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.HashMap;
- public class TCPServer {
- private ServerSocket server;
- private HashMap<Integer, Socket> activeConnections;
- // todo: Get the required connection
- public Socket getConnection(int id) {
- return activeConnections.getOrDefault(id,null);
- }
- // todo: Add connected client to the hash map
- void addConnection(int id, Socket connection) {
- activeConnections.putIfAbsent(id,connection);
- }
- synchronized void endConnection(int id){
- activeConnections.remove(id);
- }
- //todo: Initialize server
- TCPServer(int port) throws IOException {
- server=new ServerSocket(port);
- activeConnections=new HashMap<>();
- }
- // todo: Handle server listening
- // todo: For each connection, start a separate
- // todo: thread (ServerWorkerThread) to handle the communication
- void listen() throws Exception {
- while(true)
- {
- Socket client=server.accept();
- new ServerWorkerThread(client,this).start();
- }
- }
- public static void main(String[] args) throws Exception {
- TCPServer server=new TCPServer(9876);
- server.listen();
- }
- }
- class ServerWorkerThread extends Thread {
- private TCPServer server;
- private Socket socket;
- private int id;
- private DataInputStream dis;
- private DataOutputStream dos;
- public ServerWorkerThread(Socket socket, TCPServer server) throws Exception {
- this.server = server;
- this.socket = socket;
- dis = new DataInputStream(socket.getInputStream());
- dos = new DataOutputStream(socket.getOutputStream());
- id = dis.readInt();
- server.addConnection(id,socket);
- }
- @Override
- public void run()
- {
- while (true)
- {
- try {
- String line= dis.readUTF();
- if(line.equals("END"))
- {
- server.endConnection(id);
- dos=new DataOutputStream(socket.getOutputStream());
- dos.writeUTF("END");
- dos.flush();
- break;
- }
- String lines[]=line.split(":");
- Socket connection=server.getConnection(Integer.parseInt(lines[1]));
- dos=new DataOutputStream(connection.getOutputStream());
- dos.writeUTF(lines[0]);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement