C#使用Socket实现局域网聊天

2019-12-30 19:34:44王冬梅

Client客户端


using System; 
using System.Drawing; 
using System.Windows.Forms; 
using System.Threading; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Text; 
using System.Text.RegularExpressions; 
 
namespace Client 
{ 
  public partial class MainForm : Form 
  { 
    private System.Windows.Forms.Timer closeWindowTimer; 
     
    private StreamReader sr; 
    private StreamWriter sw; 
    private TcpClient tc; 
    private ClientLong cl; 
    private bool tag = true; 
       
    public MainForm(TcpClient tcp,ClientLong clo) 
    { 
      cl = clo; 
      tc = tcp; 
      InitializeComponent(); 
      Control.CheckForIllegalCrossThreadCalls = false; 
      bu_simple.Hide(); 
    } 
    void ClientFromLoad(object sender, EventArgs e) 
    { 
      PiayCheckedChanged(); 
    } 
     
    /*事件方法*/ 
    public void PiayCheckedChanged() 
    { 
      closeWindowTimer = new System.Windows.Forms.Timer(); 
      closeWindowTimer.Interval = 1000; 
      closeWindowTimer.Tick += new EventHandler(theout); 
      closeWindowTimer.Start(); 
    } 
     
    /*执行的事件*/ 
    public void theout(object source, EventArgs e) 
    { 
      //这里单独开一个线程用来显示信息 
      try{ 
        Thread t1 = new Thread(new ThreadStart(readMsg)); 
        t1.Start(); 
      }catch(Exception) 
      { 
      } 
    } 
    void readMsg() 
    { 
      if(tag && tc!=null){ 
        sr = new StreamReader(tc.GetStream()); 
        String msg = sr.ReadLine(); 
        String[] address = Regex.Split(msg,"<@=@>"); 
        chatText.AppendText(address[0].Replace("<br>","rn")); 
        address = Regex.Split(address[1],"<@>"); 
        cb_chatList.Items.Clear(); 
        foreach (String s in address) 
        { 
          if(!String.IsNullOrEmpty(s) && s != cl.clientName) 
            cb_chatList.Items.Add(s);         
        } 
      } 
    } 
    void Button1Click(object sender, EventArgs e) 
    { 
      if(String.IsNullOrEmpty(textBox2.Text)){ 
        MessageBox.Show("请输入消息");return; 
      } 
      sw = new StreamWriter(tc.GetStream()); 
      sw.WriteLine("<br>"+cl.clientName+"  "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"<br> "+textBox2.Text); 
      textBox2.Text = ""; 
      sw.Flush(); 
    } 
    void Bu_exitClick(object sender, EventArgs e) 
    { 
      MainFormFormClosing(null,null); 
    } 
    void Button2Click(object sender, EventArgs e) 
    { 
      chatText.Text = "";  
    } 
    void MainFormFormClosing(object sender, FormClosingEventArgs e) 
    { 
      closeWindowTimer.Stop(); 
      cl.Close(); 
      tag = false; 
      if(sr!=null) 
        sr.Close(); 
      if(sw!=null) 
        sw.Close(); 
    } 
    void Bu_simpleClick(object sender, EventArgs e) 
    { 
      String selected = cb_chatList.Text; 
      if(selected==null) 
      { 
        MessageBox.Show("请选择单聊对象"); 
        return; 
      } 
    } 
  } 
}