多线程 聊天程序

package Ltian;//服务器
import java.net.ServerSocket;
import java.net.Socket;

public class L1 {
 public static void main(String[] args) {
  try{
   ServerSocket ss = new   ServerSocket(9898);
   Socket server = ss.accept();
  new Thread(new L3(server.getInputStream())).start();
  new Thread(new L4("服务器",server.getOutputStream())).start();
   
   
  }catch(Exception e) {
   
  }
 }
 private static void ServerSocket() {
  
  
 }
}
2.//客户端
package Ltian;
import java.net.ServerSocket;
import java.net.Socket;
public class L2 {
 
  public static void main(String[] args) {
   try{
    Socket c = new   Socket("192.168.0.116",9898);
    
   new Thread(new L3(c.getInputStream())).start();
   new Thread(new L4("王情报",c.getOutputStream())).start();
    
    
   }catch(Exception e) {
    
   }
 }
}
三 //发送消息
package Ltian;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class L3 implements Runnable{
      private InputStream is;
 @Override
 public void run() {
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  while(true) {
   String mess;
   try {
    mess = br.readLine();
    System.out.println(mess + "\r\n");
   } catch (IOException e) {
    System.out.println("再见啊妹妹");
    break;
    
    
   }
  }
  
  
 }
 public L3(InputStream is) {
  super();
  this.is = is;
 }
 public L3() {
  super();
  
 }
 public InputStream getIs() {
  return is;
 }
 public void setIs(InputStream is) {
  this.is = is;
 }
 
  
 }
 四//接收消息
package Ltian;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class L4 implements Runnable{
 private String from;
 private OutputStream os;
 public String getFrom() {
  return from;
 }
 public void setFrom(String from) {
  this.from = from;
 }
 public OutputStream getOs() {
  return os;
 }
 public void setOs(OutputStream os) {
  this.os = os;
 }
 @Override
 public void run() {
  PrintWriter out = new PrintWriter(os);
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  while(true){
   Scanner sc = new Scanner(System.in);
   String msg =  from + ":"+sc.nextLine()+"["+sdf.format(new Date())+"]\r\n";
   out.print(msg);
   out.flush();
  }
  
 }
 public L4(String from, OutputStream os) {
  super();
  this.from = from;
  this.os = os;
 }
 public L4() {
  super();
  
 }
 
}
posted @ 2020-06-18 20:43  信王勤宝  阅读(158)  评论(0编辑  收藏  举报