1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
import java.net.*;
import java.io.*;
import java.security.*;
public class KKMultiServerThread implements Runnable {
private Socket server;
private String line,input;
private String[] clients= new String[10];
int i=0;
KKMultiServerThread(Socket server) {
this.server=server;
}
public void run () {
input="";
try {
// Get input from the client
PrintWriter out = new PrintWriter(server.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
while((line = in.readLine()) != null) {
if(line.equals("client")){
System.out.println("in if");
clients[i]=line+i;
int j=0;
while(j<i){
System.out.println(clients[j]);
j++;
}
}else{
input=line;
System.out.println(line);
out.println("I got:" + line);
}
i++;
}
// Now write to the client
System.out.println("Overall message is:" + input);
out.println("Overall message is:" + input);
server.close();
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
======================serveur
import java.net.*;
import java.io.*;
import java.security.*;
public class KKMultiServer {
private static int port=1010, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
ServerSocket listener=null;
try{
listener = new ServerSocket(port,10);
System.out.println("Server start--------->");
}catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
while(true){//(i++ < maxConnections) || (maxConnections == 0)
KKMultiServerThread connection;
try{
connection = new KKMultiServerThread(listener.accept());
Thread t = new Thread(connection);
t.start();
}catch(IOException ioe){
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
} |
Partager