软件推荐 ---一款优秀的通讯组件 HP_Socket

* HP-Socket 官方网站:http://www.jessma.org
* HP-Socket 项目主页:http://www.oschina.net/p/hp-socket
* HP-Socket 开发文档:http://www.oschina.net/p/hp-socket/docgit

 

HP-Socket 源代码下载地址:https://github.com/ldcsaa/HP-Socketgithub

自动处理了底层通讯的不少东西封装的很好,使用方便 ,提供了丰富的事件支持socket

 

//服务端tcp

//显示消息
delegate void ShowMsg(int connid, string msg);网站

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}this

HPSocketCS.TcpServer tcpServer = new HPSocketCS.TcpServer()
{
IpAddress = "192.168.3.61",
Port = 8858
};.net


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;
}orm

/// <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 = ""; } } }

相关文章
相关标签/搜索