1 package coreBookSocket;
2
3 import java.io.IOException;
4 import java.net.ServerSocket;
5 import java.net.Socket;
6
7 /*
8 * 这个方法的主要目地是为了用多线程的方法实现网络编程,让多个客户端可以同时连接到一个服务器
9 *1:准备工作和单个客户端编程类似,先建立服务器端的套接字,同时让服务器那边调用accept()方法来接受服务器端的信息,并且返回一个Socket客户端套接字
10 *2:这里面定一个while循环主要是为了让多线程能够一直持续的进行下去,为此while循环开始执行的时候都会先建立
11 * 一个新的线程来处理服务器和客户端之间的连接
12 *3:同时定一个threadedEchoHandler来实现Runnable接口,而该类的主要作用是为了实现客户端循环通信的demo
13 * author:by XIA
14 * data:9.26.2016
15 */
16 public class SimpleServerOfClients {
17 public static void main(String[] args) throws IOException {
18
19 int i=1;
20 ServerSocket server=new ServerSocket(8189);
21 while(true)
22 {
23 Socket client=server.accept();
24 System.out.println("Spawning "+i);
25 Runnable r = new threadedEchoHandler(client);
26 Thread t=new Thread(r);
27 t.start();
28 i++;
29 }
30 }
31 }
package coreBookSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class threadedEchoHandler implements Runnable {
private Socket client;
public threadedEchoHandler(Socket i) {
client=i;
}
@Override
public void run() {
try {
InputStream ins=client.getInputStream();
OutputStream outs=client.getOutputStream();
Scanner in=new Scanner(ins);
PrintWriter out=new PrintWriter(outs, true);
System.out.println("Hello! Enter bye to exit!");
boolean done=false;
while(!done&&in.hasNextLine())
{
String line = in.nextLine();
System.out.println("回应:" + line);
if (line.trim().equalsIgnoreCase("bye"))
{
done=true;
}
}
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}