码迷,mamicode.com
首页 > 编程语言 > 详细

多线程 聊天程序

时间:2020-06-18 21:54:00      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:cep   try   next   date()   util   start   his   bre   edr   

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

多线程 聊天程序

标签:cep   try   next   date()   util   start   his   bre   edr   

原文地址:https://www.cnblogs.com/wangqianbao/p/13159937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!