C#使用Socket实现局域网聊天
本文实例为大家分享了C#使用Socket实现局域网聊天的具体代码,供大家参考,具体内容如下
先运行一个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+"<@=@>"+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,"<@=@>"); 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.上传下载文件、聊天表情、私聊、踢人.......都是可以扩展的功能。
只是目前还没有可执行的思路,希望有相同爱好者多多提出宝贵意见,我会继续关注。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
您可能感兴趣的文章
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新闻效果的方法
- 01-10C#实现清空回收站的方法
- 01-10C#实现读取注册表监控当前操作系统已安装软件变化的方法
- 01-10C#实现多线程下载文件的方法
- 01-10C#实现Winform中打开网页页面的方法
- 01-10C#实现远程关闭计算机或重启计算机的方法
- 01-10C#自定义签名章实现方法
- 01-10C#文件断点续传实现方法
- 01-10winform实现创建最前端窗体的方法
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-10SublimeText编译C开发环境设置
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 01-10delphi制作wav文件的方法
- 01-11ajax实现页面的局部加载
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 01-10C#中split用法实例总结
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 04-02jquery与jsp,用jquery