Mega Code Archive

 
Categories / Java / Network Protocol
 

Start new thread for each client

import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class Main {   public static void main(String args[]) throws Exception {     ServerSocket ssock = new ServerSocket(1234);     while (true) {       Socket sock = ssock.accept();       new SocketThread(sock).start();     }   } } class SocketThread extends Thread {   Socket csocket;   public SocketThread(Socket csocket) {     this.csocket = csocket;   }   public void run() {     try {       PrintStream pstream = new PrintStream(csocket.getOutputStream());       for (int i = 10; i >= 0; i--) {         pstream.println(i);       }       pstream.close();       csocket.close();     } catch (IOException e) {       System.out.println(e);     }   } }