欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的网络多客户端通信例子

程序员文章站 2022-03-15 22:05:00
...
[color=red]一个简单的多客户端回答问题服务端,可以自动记录hashmap里没有的问题。
代码很简单,容易看懂 就不做解释了[/color]


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;


public class ServerTest {


public static void main(String[] args) {
ServerTest serverTest=new ServerTest();
HashMap<String, String> quesMap = serverTest.creatMap();

try {
int i=1;
ServerSocket serverSocket=new ServerSocket(8189);
System.out.println("服务端启动,等待客户端连接...");
while (true) {
Socket incoming=serverSocket.accept();
System.out.println("连接数 "+i);
Runnable r =new ThreadHandler(incoming,quesMap);
Thread t = new Thread(r);
t.start();
i++;
}

} catch (IOException e) {
e.printStackTrace();
}

}

public HashMap<String, String> creatMap(){
HashMap<String, String> quesMap= new HashMap<String, String>();
quesMap.put("what is your name?", "my name is otto");
quesMap.put("what is your age?", "i'm 24");
return quesMap;
}

}




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;

public class ThreadHandler implements Runnable{

public ThreadHandler(Socket i,HashMap<String, String> hashMap){
this.hashMap=hashMap;
this.incoming=i;
}


public void run() {
try{
try {
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();

Scanner inScanner= new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream,true);

out.println("you can type EXIT to exit!");
out.println("**************************");
System.out.println("已经链接!");
boolean done = false;
boolean locked = false;
String key=null;
while (!done && inScanner.hasNextLine()) {
String line=inScanner.nextLine();
System.out.println(line);
if(!locked && hashMap.containsKey(line)){
out.println("Echo :"+hashMap.get(line));

}else{
if(locked==true){
hashMap.put(key,line);
locked=false;
out.println("Echo:问题和答案已经保存!");
}else {
out.println("Echo:抱歉,目前只能回答有限问题!");
out.println("但是系统将记录你的问题,如知道答案,请输入");
key=line;
locked = true;
}


}
if(line.trim().equals("EXIT"))done=true;

}


} finally{
incoming.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}

private Socket incoming;
private HashMap<String, String> hashMap;
}