C#使用Socket實(shí)現(xiàn)局域網(wǎng)聊天
本文實(shí)例為大家分享了C#使用Socket實(shí)現(xiàn)局域網(wǎng)聊天的具體代碼,供大家參考,具體內(nèi)容如下
先運(yùn)行一個(gè)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ù)端,并且啟動(dòng)
try{
listener = new TcpListener(IPAddress.Parse(ipAddress()),port);
listener.Start();
bu_Start.Enabled = false;
bu_stop.Enabled = true;
}catch(Exception ex)
{
MessageBox.Show("服務(wù)器啟動(dòng)失敗, 原因:"+ex.Message);
bu_Start.Enabled = true;
bu_stop.Enabled = false;
return;
}
selectChat.Text = "服務(wù)器啟動(dòng)成功,訪問IP:"+ipAddress()+" 端口號(hào):"+port;
//記錄住連接的客戶端
socketList = new Dictionary<String,TcpClient>();
charList = new StringBuilder();
//使用多線程,用于多個(gè)客戶端接入
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ù)計(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ú)開一個(gè)線程用來顯示信息
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("請(qǐng)輸入消息");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("請(qǐng)選擇單聊對(duì)象");
return;
}
}
}
}
補(bǔ)充:
1.上傳下載文件、聊天表情、私聊、踢人.......都是可以擴(kuò)展的功能。
只是目前還沒有可執(zhí)行的思路,希望有相同愛好者多多提出寶貴意見,我會(huì)繼續(xù)關(guān)注。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#使用WebSocket實(shí)現(xiàn)聊天室功能
- C#使用Socket實(shí)現(xiàn)本地多人聊天室
- C#基于Socket實(shí)現(xiàn)多人聊天功能
- c#基于WinForm的Socket實(shí)現(xiàn)簡單的聊天室 IM
- C# Socket編程實(shí)現(xiàn)簡單的局域網(wǎng)聊天器的示例代碼
- C#使用Socket實(shí)現(xiàn)服務(wù)器與多個(gè)客戶端通信(簡單的聊天系統(tǒng))
- 基于c#用Socket做一個(gè)局域網(wǎng)聊天工具
- 分享一個(gè)C#編寫簡單的聊天程序(詳細(xì)介紹)
- C#制作簡單的多人在線即時(shí)交流聊天室
- C#用websocket實(shí)現(xiàn)簡易聊天功能(服務(wù)端)
相關(guān)文章
C#枚舉類型與結(jié)構(gòu)類型實(shí)例解析
這篇文章主要介紹了C#枚舉類型與結(jié)構(gòu)類型實(shí)例,需要的朋友可以參考下2014-07-07
C#實(shí)現(xiàn)簡單的計(jì)算器功能完整實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)簡單的計(jì)算器功能,結(jié)合完整實(shí)例形式分析了C#實(shí)現(xiàn)常見的數(shù)學(xué)運(yùn)算、進(jìn)制轉(zhuǎn)換等相關(guān)操作技巧與界面布局方法,需要的朋友可以參考下2017-08-08
基于C#的音樂播放器主Form實(shí)現(xiàn)代碼
這篇文章主要介紹了基于C#的音樂播放器主Form實(shí)現(xiàn)代碼,很實(shí)用的功能,需要的朋友可以參考下2014-08-08
WPF拖動(dòng)DataGrid滾動(dòng)條時(shí)內(nèi)容混亂的解決方法
這篇文章主要介紹了WPF拖動(dòng)DataGrid滾動(dòng)條時(shí)內(nèi)容混亂的解決方法2016-10-10
C#實(shí)現(xiàn)泛型List分組輸出元素的方法
這篇文章主要介紹了C#實(shí)現(xiàn)泛型List分組輸出元素的方法,涉及C#針對(duì)List的遍歷、排序、輸出等相關(guān)操作技巧,需要的朋友可以參考下2017-12-12

