今天在复习网络线程和安全的时候,偶然发现了好久写的一个简易聊天室,给大家分享分享:
package com.yc.bean2;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import javax.net.ssl.SSLContext;
/**
* 基于Socket的简易聊天室
* @author cyj
*
*/
//服务器端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(30040); //指定端口号
System.out.println("服务器启动了,监听客户的连接。。。");
while(true){
Socket s=ss.accept();//总是监听客户端
System.out.println("客户端"+s.getInetAddress()+"连接上啦");
Thread t=new Thread( new TalkTask(s));
t.start();
}
}
}
class TalkTask implements Runnable{
private Socket s;
private Scanner sc;
private PrintWriter pw;
private Scanner keyboard=new Scanner(System.in);
public TalkTask(Socket s) throws IOException {
this.s=s;
sc=new Scanner(s.getInputStream());
pw=new PrintWriter(s.getOutputStream(),true);
}
@Override
public void run() {
String line=sc.nextLine();
System.out.println("客户端"+s.getInetAddress()+":"+line);
System.out.println("服务器的回应是:");
String answer=keyboard.nextLine();
while(!answer.equals("bye")){
pw.println(answer);
System.out.println("服务器:"+answer);
if(s!=null&& !s.isClosed() && s.isConnected() && sc.hasNextLine()){
System.out.println("客户端"+s.getInetAddress()+":"+sc.nextLine());
System.out.println("服务器的回应是:");
answer=keyboard.nextLine();
}else{
answer="bye";
}
}
System.out.println("与客户端"+s.getInetAddress()+"断开");
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//客户端
package com.yc.bean2;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client1 {
public static void main(String[] args) throws IOException {
Socket s=new Socket("localhost",30040);
PrintWriter pw=null;
Scanner sc=null;
Scanner keyboard=new Scanner(System.in);//从键盘输入响应
sc=new Scanner( s.getInputStream());//将bufferedInputStream改为Scanner 目的就一次读一行数据
pw=new PrintWriter(s.getOutputStream(),true);
System.out.println("请输入您要对服务器说的话:");
String line=keyboard.nextLine();
while(!line.equals("bye")){
pw.println(line);
System.out.println("客户端:"+line);
if(s!=null&& !s.isClosed() && s.isConnected() && sc.hasNextLine()){
String serveranswer=sc.nextLine();
System.out.println("服务器说:"+serveranswer);
System.out.println("请输入您要对服务器说的话:");
line=keyboard.nextLine();
}else{
line="bye";
}
}
s.close();
}
}