* HP-Socket 官方网站:http://www.jessma.org* HP-Socket 项目主页:http://www.oschina.net/p/hp-socket* HP-Socket 开发文档:http://www.oschina.net/p/hp-socket/doc
HP-Socket 源代码下载地址:https://github.com/ldcsaa/HP-Socket
自动处理了底层通信的很多东西封装的很好,使用方便 ,提供了丰富的事件支持
//服务端
//显示消息 delegate void ShowMsg(int connid, string msg);
public partial class Form1 : Form { public Form1() { InitializeComponent(); }
HPSocketCS.TcpServer tcpServer = new HPSocketCS.TcpServer() { IpAddress = "192.168.3.61", Port = 8858 };
private void Form1_Load(object sender, EventArgs e) { tcpServer.OnAccept += httpServer_OnAccept; tcpServer.OnReceive += httpServer_OnReceive; } //启动 private void button1_Click(object sender, EventArgs e) { textBox1.Text += tcpServer.IpAddress + ":" + tcpServer.Port + " 开始监听:\n"; tcpServer.Start(); } /// <summary> /// 监听到连接 /// </summary> /// <param name="connId"></param> /// <param name="pClient"></param> /// <returns></returns> public HandleResult httpServer_OnAccept(IntPtr connId, IntPtr pClient) { ShowMsg showMsg = new ShowMsg((connid, msg) => { textBox1.Text += string.Format("客户端{0}:{1}\n", connid, msg); }); this.Invoke(showMsg, new object[] { connId.ToInt32(), "我上线了..." }); return HandleResult.Ok; }
/// <summary> /// /// </summary> /// <param name="connId"></param> /// <param name="bytes"></param> /// <returns></returns> public HandleResult httpServer_OnReceive(IntPtr connId, byte[] bytes) { ShowMsg showMsg = new ShowMsg((connid, msg) => { textBox1.Text += string.Format("客户端{0}说:{1}\n", connid, msg); }); this.Invoke(showMsg, new object[] { connId.ToInt32(), Encoding.Default.GetString(bytes) }); return HandleResult.Ok; }
}
//客户端
public partial class Form1 : Form { HPSocketCS.TcpClient tcpClient; public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { tcpClient = new HPSocketCS.TcpClient(); bool connected = tcpClient.Connect("192.168.3.61", 8858); if (connected) { textBox1.Text += (tcpClient.ConnectionId + ":已经连接"); } }
private void button1_Click(object sender, EventArgs e) { string msg = textBox2.Text.Trim(); var bytes=Encoding.Default.GetBytes(msg); bool sended = tcpClient.Send(bytes, 0, bytes.Length); if (sended) { textBox1.Text += (tcpClient.ConnectionId + ":" + msg); textBox2.Text = ""; } } }
转载于:https://www.cnblogs.com/yaoweijun/p/8442923.html
相关资源:C# socket封装类和组件含例程全部开源