import java.io.*;
import java.net.*;
public class MultiClientServer implements Runnable{
static int SerialNum = 0; //每個Client的序號。
Socket socket;
public MultiClientServer(Socket ss){
socket = ss;
}
public static void main (String args[]){
int MaxClientNum = 5;
try{
//建立Server Socket。
ServerSocket server = new ServerSocket(1680);
for( int i = 0; i<MaxClientNum;i++){
Socket socket=server.accept();//監聽為作出此通訊端串連到並接受它。
//串連建立,建立一個Server端線程與Client端通訊。
Thread t = new Thread(new MultiClientServer(socket));
t.start();
}
server.close(); //關閉Server Socket。
}catch(Exception e){
System.out.println("Error:"+e);
}
}
//Server端通訊線程的線程體。
public void run(){
int myNum = ++SerialNum;
try{
//通過Socket擷取串連上的輸入/輸出流。
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
//建立標準輸入資料流,從鍵盤接收資料。
BufferedReader sin=new BufferedReader(
new InputStreamReader(System.in));//替換音樂路徑
/* 先讀取Client發送的資料,然後從標準輸入讀取資料發送給Client。
當接收到bye時關閉串連。*/
String s;
while(!(s=in.readLine()).equals("bye")){
System.out.println("# Received from Client No."+myNum+": "+s);
out.println(sin.readLine());
out.flush();
}
System.out.println("The connection to Client No."+
myNum+" is closing... ... ");
//關閉串連。
in.close();
out.close();
socket.close();
}catch(Exception e){
System.out.println("Error:"+e);
}
}
}
伺服器端
import java.io.*;
import java.net.*;
public class MyClient{
public static void main (String args[]){
try{
Socket socket = new Socket("127.0.0.1",1680); //發出串連請求。
//本機電腦類比 使用1680連接埠
//串連建立,通過Socket擷取串連上的輸入/輸出流。
PrintWriter out = new PrintWriter(socket.getOutputStream());
//發送輸出資料流 //OutputStream類型的
BufferedReader in = new BufferedReader(
new InputStreamReader (socket.getInputStream()));
//得到伺服器輸入資料流
//建立標準輸入資料流,從鍵盤接收資料。
BufferedReader sin = new BufferedReader(
new InputStreamReader (System.in));
//從標準輸入中讀取一行,發送Server端,當使用者輸入bye時結束串連。
String s;
do{
s=sin.readLine();
out.println(s);
out.flush();
if (!s.equals("bye")){
System.out.println("@ Server response: "+in.readLine());
}
else{
System.out.println("The connection is closing... ... ");
}
}while(!s.equals("bye"));
//關閉串連。
out.close();
in.close();
socket.close();
}catch (Exception e) {
System.out.println("Error"+e);
}
}
}
使用者端