C#使用Socket實(shí)現(xiàn)局域網(wǎng)聊天
本文實(shí)例為大家分享了C#使用Socket實(shí)現(xiàn)局域網(wǎng)聊天的具體代碼,供大家參考,具體內(nèi)容如下
先運(yùn)行一個java寫的局域網(wǎng)聊天,效果圖如下
后使用c#圖形修改如下:
C#代碼:
servlet服務(wù)端
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;
//創(chuàng)建服務(wù)端,并且啟動
try{
listener = new TcpListener(IPAddress.Parse(ipAddress()),port);
listener.Start();
bu_Start.Enabled = false;
bu_stop.Enabled = true;
}catch(Exception ex)
{
MessageBox.Show("服務(wù)器啟動失敗, 原因:"+ex.Message);
bu_Start.Enabled = true;
bu_stop.Enabled = false;
return;
}
selectChat.Text = "服務(wù)器啟動成功,訪問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)
{
//永久監(jiān)聽讀取客戶端
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+"<@=@>"+charList.ToString());
sw.Flush();
}
}
}
/*根據(jù)計算名獲取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();
}
/*執(zhí)行的事件*/
public void theout(object source, EventArgs e)
{
//這里單獨(dú)開一個線程用來顯示信息
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>","\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;
}
}
}
}
補(bǔ)充:
1.上傳下載文件、聊天表情、私聊、踢人.......都是可以擴(kuò)展的功能。
只是目前還沒有可執(zhí)行的思路,希望有相同愛好者多多提出寶貴意見,我會繼續(xù)關(guān)注。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
上一篇:C# 數(shù)據(jù)庫鏈接字符串加密解密工具代碼詳解
欄 目:C#教程
下一篇:ASP.Net動態(tài)讀取Excel文件最簡方法
本文標(biāo)題:C#使用Socket實(shí)現(xiàn)局域網(wǎng)聊天
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5186.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動新聞效果的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已安裝軟件變化的方法
- 01-10C#實(shí)現(xiàn)多線程下載文件的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10C#實(shí)現(xiàn)遠(yuǎn)程關(guān)閉計算機(jī)或重啟計算機(jī)的方法
- 01-10C#自定義簽名章實(shí)現(xiàn)方法
- 01-10C#文件斷點(diǎn)續(xù)傳實(shí)現(xiàn)方法
- 01-10winform實(shí)現(xiàn)創(chuàng)建最前端窗體的方法


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 04-02jquery與jsp,用jquery


