实例介绍
【实例简介】
【实例截图】
【核心代码】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace Socket_Server { public partial class FormServer : Form { System.Collections.Generic.List<User> userList = new List<User>(); //连接的用户 private delegate void SetListBoxCallback(string str); //回调Listbox的委托事件,及时显示互动信息 private SetListBoxCallback setListBoxCallback; private delegate void SetComboBoxCallback(User user); //回调ComboBox的委托事件,获取Client数 private SetComboBoxCallback setComboBoxCallback; IPAddress localAddress; //使用的本机IP地址 private int port = 51888; //监听端口 private TcpListener myListener; //网络客户端的连接 监听对象 public FormServer() { InitializeComponent(); } private void FormServer_Load(object sender, EventArgs e) { //加载回调函数 listBoxStatus.HorizontalScrollbar = true; setListBoxCallback = new SetListBoxCallback(SetListBox); setComboBoxCallback = new SetComboBoxCallback(AddComboBoxitem); //获取主机名,使用本机IP IPAddress[] addrIP = Dns.GetHostAddresses(Dns.GetHostName()); localAddress = addrIP[0]; buttonStop.Enabled = false; } #region 开启 监听服务 /// <summary> /// 开启 监听服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonStart_Click(object sender, EventArgs e) { myListener = new TcpListener(localAddress, port); myListener.Start(); SetListBox(string.Format("开始在{0}:{1}监听客户连接", localAddress, port)); //创建一个线程监听客户端连接请求 ThreadStart ts = new ThreadStart(ListenClientConnect); Thread myThread = new Thread(ts); myThread.Start(); buttonStart.Enabled = false; buttonStop.Enabled = true; } #endregion #region 停止 监听服务 /// <summary> /// 停止 监听服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonStop_Click(object sender, EventArgs e) { SetListBox(string.Format("目前连接用户数:{0}", userList.Count)); SetListBox("开始停止服务,并依次使用户退出!"); for (int i = 0; i < userList.Count; i ) { comboBoxReceiver.Items.Remove(userList[i].client.Client.RemoteEndPoint); userList[i].br.Close(); userList[i].bw.Close(); userList[i].client.Close(); } //通过停止监听让myListener.AcceptTcpClient()产生异常退出监听线程 myListener.Stop(); buttonStart.Enabled = true; buttonStop.Enabled = false; } #endregion #region 发送反馈 至Client /// <summary> /// 发送反馈 至Client /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonSend_Click(object sender, EventArgs e) { int index = comboBoxReceiver.SelectedIndex; if (index == -1) { MessageBox.Show("请先选择接收方,然后再单击〔发送〕"); } else { User user = (User)userList[index]; SendToClient(user, textBoxSend.Text); textBoxSend.Clear(); } } #endregion #region 接收客户端连接请求 /// <summary> /// 接收客户端连接请求 /// </summary> private void ListenClientConnect() { while (true) { TcpClient newClient = null; try { //等待用户进入 newClient = myListener.AcceptTcpClient(); } catch { //当单击“停止监听”或者退出此窗体时AcceptTcpClient()会产生异常 //因此可以利用此异常退出循环 break; } //每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息 ParameterizedThreadStart pts = new ParameterizedThreadStart(ReceiveData); Thread threadReceive = new Thread(pts); User user = new User(newClient); threadReceive.Start(user); userList.Add(user); AddComboBoxitem(user); SetListBox(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint)); SetListBox(string.Format("当前连接用户数:{0}", userList.Count)); } } #endregion #region 接收、处理客户端信息,每客户1个线程,参数用于区分是哪个客户 /// <summary> /// 接收、处理客户端信息,每客户1个线程,参数用于区分是哪个客户 /// </summary> /// <param name="obj"></param> private void ReceiveData(object obj) { User user = (User)obj; TcpClient client = user.client; //是否正常退出接收线程 bool normalExit = false; //用于控制是否退出循环 bool exitWhile = false; while (exitWhile == false) { string receiveString = null; try { //从网络流中读出字符串 //此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串 receiveString = user.br.ReadString(); } catch { //底层套接字不存在时会出现异常 SetListBox("接收数据失败"); } if (receiveString == null) { if (normalExit == false) { //如果停止了监听,Connected为false if (client.Connected == true) { SetListBox(string.Format( "与[{0}]失去联系,已终止接收该用户信息", client.Client.RemoteEndPoint)); } } break; } SetListBox(string.Format("来自[{0}]:{1}", user.client.Client.RemoteEndPoint, receiveString)); string[] splitString = receiveString.Split(','); string sendString = ""; switch (splitString[0]) { case "Login": //格式:Login sendString = "Hello,我是服务器,你好!"; SendToClient(user, sendString); break; case "Logout": //格式:Logout SetListBox(string.Format("[{0}]退出", user.client.Client.RemoteEndPoint)); normalExit = true; exitWhile = true; break; case "Talk": //格式:Talk,对话内容 SetListBox(string.Format("[{0}]说:{1}", client.Client.RemoteEndPoint, receiveString.Substring(splitString[0].Length 1))); break; default: SetListBox("什么意思啊:" receiveString); break; } } userList.Remove(user); client.Close(); SetListBox(string.Format("当前连接用户数:{0}", userList.Count)); } #endregion #region 发送数据 至Client /// <summary> /// 发送数据 至Client /// </summary> /// <param name="user"></param> /// <param name="str"></param> private void SendToClient(User user, string str) { try { //将字符串写入网络流,此方法会自动附加字符串长度前缀 user.bw.Write(str); user.bw.Flush(); SetListBox(string.Format("向[{0}]发送:{1}", user.client.Client.RemoteEndPoint, str)); } catch { SetListBox(string.Format("向[{0}]发送信息失败", user.client.Client.RemoteEndPoint)); } } #endregion #region 回调 向ComboxBox自动添加Client /// <summary> /// 回调 向ComboxBox自动添加Client /// </summary> /// <param name="user"></param> private void AddComboBoxitem(User user) { if (comboBoxReceiver.InvokeRequired == true) { this.Invoke(setComboBoxCallback, user); } else { comboBoxReceiver.Items.Add(user.client.Client.RemoteEndPoint); } } #endregion #region 回调 SetListBox及时更新显示 和SERVER的互动信息 /// <summary> /// 回调 SetListBox及时更新显示 和SERVER的互动信息 /// </summary> /// <param name="str"></param> private void SetListBox(string str) { if (listBoxStatus.InvokeRequired == true) { this.Invoke(setListBoxCallback, str); } else { listBoxStatus.Items.Add(str); listBoxStatus.SelectedIndex = listBoxStatus.Items.Count - 1; listBoxStatus.ClearSelected(); } } #endregion #region 文本框 键盘事件 /// <summary> /// 文本框 键盘事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBoxSend_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return) { buttonSend_Click(null, null); } } #endregion #region 关闭窗体 释放资源 /// <summary> /// 关闭窗体 释放资源 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FormServer_FormClosing(object sender, FormClosingEventArgs e) { //未单击开始监听就直接退出时,myListener为null if (myListener != null) { buttonStop_Click(null, null); } } #endregion } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论