簡單 《實現區域網路聊天室》----待更新...

來源:互聯網
上載者:User

標籤:tcp   網路編程   

先運行一個java寫的區域網路聊天,如下



後使用c#圖形修改如下:


c#代碼:

servlet服務端

using System;using System.Collections.Generic;using System.Drawing;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.Threading;using System.IO;using System.Text;using System.Text.RegularExpressions;namespace Server{public partial class MainForm : Form{private TcpListener listener;private Dictionary<String,TcpClient> socketList;private bool tag = true;private StringBuilder charList;public MainForm(){InitializeComponent();Control.CheckForIllegalCrossThreadCalls = false;}void Bu_StartClick(object sender, EventArgs e){cb_chatList.Items.Clear();selectChat.Text="";int port = 8888;//建立服務端,並且啟動try{listener = new TcpListener(IPAddress.Parse(ipAddress()),port);listener.Start();bu_Start.Enabled = false;bu_stop.Enabled = true;}catch(Exception ex){MessageBox.Show("伺服器啟動失敗, 原因:"+ex.Message);bu_Start.Enabled = true;bu_stop.Enabled = false;return;}selectChat.Text = "伺服器啟動成功,訪問IP:"+ipAddress()+"  連接埠號碼:"+port;//記錄住串連的用戶端socketList = new Dictionary<String,TcpClient>();charList = new StringBuilder();//使用多線程,用於多個用戶端接入Thread th = new Thread(new ThreadStart(executeTask));th.Start();}public void executeTask(){while(tag){//等待使用者串連TcpClient client = null;try{client = listener.AcceptTcpClient();}catch(Exception){}Thread th = new Thread(executeRead);th.Start((Object)client);}}public void executeRead(Object pamars){//永久監聽讀取用戶端TcpClient client = pamars as TcpClient;while(tag){NetworkStream ns = client.GetStream();StreamReader sr = new StreamReader(ns);String msg = String.Empty;String people = String.Empty;try {msg = sr.ReadLine();if(msg.IndexOf("<clientName>")!=-1){msg = Regex.Split(msg,"=")[1];        cb_chatList.Items.Add(msg);               charList.Append(msg).Append("<@>");socketList.Add(msg,client);msg = "<br>歡迎【"+msg+"】光臨<br>";}selectChat.AppendText(msg.Replace("<br>","\r\n"));sendMsg(String.Empty,msg);} catch (Exception) {//MessageBox.Show(ex.Message.ToString());break;}}}public void sendMsg(String target,String msg){if(String.Empty!=target){TcpClient client = socketList[target];StreamWriter sw = new StreamWriter(client.GetStream());sw.WriteLine(msg);sw.Flush();}else{Dictionary<String,TcpClient>.KeyCollection keyColl = socketList.Keys;foreach (String name in keyColl) {StreamWriter sw = new StreamWriter(socketList[name].GetStream());sw.WriteLine(msg+"<@[email protected]>"+charList.ToString());sw.Flush();}}}/*根據計算名擷取IP地址*/public String ipAddress(){IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName());return address[2].ToString();}void ServerFromFormClosing(object sender, FormClosingEventArgs e){e.Cancel = false;if(tag)tag = false;if(listener!=null)listener.Stop();}void Bu_stopClick(object sender, EventArgs e){bu_Start.Enabled = true;bu_stop.Enabled = false;if(tag)tag = false;if(listener!=null)listener.Stop();}}}


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,"<@[email protected]>");        chatText.AppendText(address[0].Replace("<br>","\r\n"));        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;}}}}

補充:

1:上傳下載檔案、聊天表情、私聊、踢人.......都是可以擴充的功能。

只是目前還有可執行檔思路,希望有相同愛好者多多提出寶貴意見。我會繼續關注。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.