基于套接字的简易版聊天室

今天在复习网络线程和安全的时候,偶然发现了好久写的一个简易聊天室,给大家分享分享:

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();
}


}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值