实例介绍
【实例简介】可添加 客户端和服务端
【实例截图】
【核心代码】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using SocketTool.Core; using System.Threading; using System.Diagnostics; //|5|1|a|s|p|x namespace SocketTool { public partial class ClientForm : Form, ISocketInfo { public ClientForm() { InitializeComponent(); SocketInfo = new SocketInfo(); } private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ClientForm)); private IClient socketClient = new CommTcpClient(); private Thread SendOutgoingThread ; private int sendInterval = 0; private Boolean IsAutoSend; private Boolean continueSend = false; private string sendContent; private string errorMsg = ""; public SocketInfo SocketInfo {get;set;} private void btnSend_Click(object sender, EventArgs e) { if (rbUdp.Checked) socketClient = new CommUdpClient(); socketClient.OnDataReceived = new ReceivedHandler(ListenMessage); socketClient.OnSocketError = new SocketErrorHandler(ListenErrorMessage); string ServerIP = this.txtIP.Text; errorMsg = ""; if (string.IsNullOrEmpty(ServerIP)) errorMsg = "请输入合法的IP地址"; try { int Port = int.Parse(this.txtPort.Text); socketClient.Init(ServerIP, Port); } catch (Exception ex) { errorMsg = "请输入合法的端口"; } sendContent = this.rtSendData.Text; if (string.IsNullOrEmpty(sendContent)) errorMsg = "请输入要发送的内容"; if (cbAutoSend.Checked) { try { sendInterval = int.Parse(txtInterval.Text) * 1000; } catch (Exception ex) { errorMsg = "请输入整数的发送时间间隔"; } IsAutoSend = true; } if (string.IsNullOrEmpty(errorMsg) == false) { MessageBox.Show(errorMsg); return; } continueSend = true; btnDisconnect.Enabled = true; btnSend.Enabled = IsAutoSend == false; SendOutgoingThread = new Thread(new ThreadStart(SendThreadFunc)); SendOutgoingThread.Start(); /** else { if (string.IsNullOrEmpty(errorMsg) == false) { MessageBox.Show(errorMsg); return; } byte[] data = System.Text.Encoding.Default.GetBytes(sendContent); try { tcpClient.SendData(data); btnDisconnect.Enabled = true; } catch (Exception ex) { MessageBox.Show("发送数据出错,无法连接服务器"); } } */ } private void SendThreadFunc() { while (continueSend) { byte[] data = System.Text.Encoding.Default.GetBytes(sendContent); if(rbHex.Checked) { data = ParseUtil.ToByesByHex(sendContent); } try { socketClient.Send(data); } catch (Exception ex) { ListenMessage(0, "", ex.Message); break; } if (IsAutoSend == false) break; Thread.Sleep(sendInterval); } } public void ListenErrorMessage(object o, SocketEventArgs e) { string errorMsg = "[" e.ErrorCode "]" SocketUtil.DescrError(e.ErrorCode); ListenMessage((int)o, "Socket错误", errorMsg); } private void ListenMessage(object ID, string type, string msg) { if (PacketView.InvokeRequired) { try { MsgHandler d = new MsgHandler(ListenMessage); this.Invoke(d, new object[] {0,type, msg}); } catch (System.Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); } } else { if (type == "Socket错误") { continueSend = false; btnDisconnect.Enabled = false; btnSend.Enabled = true; } if (PacketView.Items.Count > 200) PacketView.Items.Clear(); ListViewItem item = PacketView.Items.Insert(0, "" PacketView.Items.Count); //int length = e.Data.Length; string strDate = DateTime.Now.ToString("HH:mm:ss"); item.SubItems.Add(strDate); item.SubItems.Add(msg); //item.SubItems.Add("" length); } } public void ListenMessage(object o, ReceivedEventArgs e) { if (PacketView.InvokeRequired) { try { ReceivedHandler d = new ReceivedHandler(ListenMessage); this.Invoke(d, new object[] {o, e }); } catch (System.Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); } } else { if (PacketView.Items.Count > 200) PacketView.Items.Clear(); ListViewItem item = PacketView.Items.Insert(0, "" PacketView.Items.Count); int length = e.Data.Length; string strDate = DateTime.Now.ToString("HH:mm:ss"); item.SubItems.Add(strDate); string msg = ParseUtil.ParseString(e.Data, length); if (rbHex.Checked) msg = ParseUtil.ToHexString(e.Data, length); item.SubItems.Add(msg); item.SubItems.Add("" length); if (cbLog.Checked) { logger.Info(e.RemoteHost.ToString() " " msg); } //item.SubItems.Add("" msg.MsgContentDesc); } } private void cbAutoSend_CheckedChanged(object sender, EventArgs e) { this.txtInterval.Enabled = cbAutoSend.Checked; } private void btnDisconnect_Click(object sender, EventArgs e) { continueSend = false; try { if (socketClient != null) socketClient.Close(); SendOutgoingThread.Abort(); } catch (Exception ex) { } this.btnSend.Enabled = true; } private void ClientForm_FormClosing(object sender, FormClosingEventArgs e) { SocketInfo.ServerIp = this.txtIP.Text; try { SocketInfo.Port = int.Parse(this.txtPort.Text); } catch (System.Exception ex) { } SocketInfo.Protocol = rbTcp.Checked ? "Tcp" : "Udp"; SocketInfo.Format = rbAscII.Checked ? "AscII" : "Hex"; SocketInfo.Type = "Client"; SocketInfo.ServerIp = this.txtIP.Text; SocketInfo.Data = this.rtSendData.Text; SocketInfo.IsAuto = cbAutoSend.Checked; try { SocketInfo.Port = int.Parse(this.txtPort.Text); } catch (Exception ex) { //errorMsg = "请输入合法的端口"; } } private void btnClearLog_Click(object sender, EventArgs e) { this.PacketView.Clear(); } private void ClientForm_Load(object sender, EventArgs e) { this.txtIP.Text = SocketInfo.ServerIp; rbTcp.Checked = SocketInfo.Protocol == "Tcp"; rbUdp.Checked = SocketInfo.Protocol != "Tcp"; rbAscII.Checked = SocketInfo.Format == "AscII"; rbHex.Checked = SocketInfo.Format != "AscII"; this.txtPort.Text = "" SocketInfo.Port; this.rtSendData.Text = SocketInfo.Data; cbAutoSend.Checked = SocketInfo.IsAuto; } private void btnOpenLog_Click(object sender, EventArgs e) { Process.Start("notepad.exe", "client.log"); } } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论