对(一)进行升级,继承线程,让服务端能够和多个客户端连接。
将读写相关的功能提出,成一个新类,在主函数中只进行开启端口的工作,读写功能放在继承 了线程的类的run函数中。
服务端主函数:
public class TelServerV3 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket ss = new ServerSocket(8888);
while (true){
Socket s = ss.accept();
System.out.printf("got client connection: %s%n", s.getRemoteSocketAddress());
MServer ms = new MServer(s);
ms.start();
System.out.printf("close client %s%n", s.getRemoteSocketAddress());
}
}
}
线程类:
public class MServer extends Thread{
Socket socket;
public MServer(Socket socket){
this.socket = socket;
}
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
BufferedReader reader = new BufferedReader(new InputStreamReader((socket.getInputStream())));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
String line = null;
while((line = reader.readLine()) !=null){
System.out.printf("get message from client: %s%n", line);
// response back to client
String now = sdf.format(new Date());
pw.println(String.format("%s - %s", now, line));
pw.flush();
}
}catch (Exception ex){
//catch it, then we can continue consumer the next client connection
System.out.printf("got error: %s%n", ex.getMessage());
ex.printStackTrace();
}
}
}
客户端:
public class LinkTestV2 {
public static void main(String[] args) throws IOException {
Socket s1 = new Socket();
s1.connect(new InetSocketAddress("127.0.0.1",8888));
Scanner m = new Scanner(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(s1.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(s1.getInputStream()));
System.out.print("please input sth:");
String line = m.nextLine();
String line2 = null;
while (line != null) {
System.out.printf("write out> %s%n", line);
pw.println(line);
pw.flush();
line2 = br.readLine();
System.out.printf("reply> %s",line2);
System.out.println();
System.out.print("please input sth:");
line = m.nextLine();
}
}
}
如何使同一个主函数多次运行?
下拉框中选择Edit Configurations... ,然后弹出新的窗口,点击Modify options,在所属下拉框中选择Allow multiple instances,前有 √ 即可。
这样就可以运行一个服务端,多次启动客户端,使用telnet也同样可以(开多个黑窗口)。每个客户端线程都会分配一个socket,这样就可以进行多对一进行通讯了。