聊天室案例V3.
重构聊天室案例,使用线程来实现一个服务器但可以同时接收多个客户端的消息.
客户端 服务端
客户A连接,发送消息
客户B连接,发送消息 服务器接收客户端发送的消息,并输出显示
客户C连接,发送消息
解决步骤:
1.首先在服务器端创建内部类,并在该内部类中设置线程要执行的任务.(接收并打印消息)
2.在服务器端中start方法中使用while(true)循环,在循环中阻塞等待多个客户端的连接,
当有客户连接时,则使用第一步定义的任务作为线程的任务,并启动一个该任务对应的线程
去处理服务器和客户端之间的通信
public class Client3 {
private Socket socket;
public Client3() {
try {
socket = new Socket("localhost", 8060);
}catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
PrintWriter pw = new PrintWriter(osw,true);
Scanner scanner = new Scanner(System.in);
while(true) {
pw.println(scanner.nextLine());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(socket!=null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Client3 c3 = new Client3();
c3.start();
}
}
public class Server3 {
private ServerSocket serversocket;
public Server3() {
try {
serversocket = new ServerSocket(8060);
} catch (IOException e) {
e.printStackTrace();
}
}
Socket socket ;
public void start() {
System.out.println("Wait Client Connect");
try {
while(true) {
socket = serversocket.accept();
System.out.println("Successful connection to client");
neibu n = new neibu();
Thread t = new Thread(n);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class neibu implements Runnable{
@Override
public void run() {
InputStream in;
try {
in = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(in,"UTF-8");
BufferedReader br = new BufferedReader(isr);
System.out.println("Client Speak:"+br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Server3 s3 = new Server3();
s3.start();
}
}