欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net的socket异步通讯示例分享

程序员文章站 2024-02-26 13:44:10
1、首先添加两个windows窗体项目,一个作为服务端server,一个作为客户端client 2、然后添加服务端代码,添加命名空间,界面上添加textbox控件 复制...

1、首先添加两个windows窗体项目,一个作为服务端server,一个作为客户端client

2、然后添加服务端代码,添加命名空间,界面上添加textbox控件

复制代码 代码如下:

using system.net;
using system.net.sockets;

3、formload方法添加代码

复制代码 代码如下:

private void form1_load(object sender, eventargs e)
        {
            ipendpoint epserver = new ipendpoint(ipaddress.parse("127.0.0.1"), 7878);//ip地址和端口号
            socket socket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);//定义socket
            socket.bind(epserver);//绑定
            socket.listen(10);//监听
            socket.beginaccept(new asynccallback(recving), socket);//异步接收,回调方法为recving
        }

4、添加回调方法代码

复制代码 代码如下:

private void recving(iasyncresult rec_socket)
        {
            string cmdstr = "";
            socket sc = (socket)rec_socket.asyncstate;
            socket socket = sc.endaccept(rec_socket);
            byte[] bytes = new byte[1024];
            int i = socket.receive(bytes);
            cmdstr = encoding.utf8.getstring(bytes, 0, i);
            showstrs(cmdstr);
            sc.beginaccept(new asynccallback(recving), sc);
        }

5、添加showstrs方法,

定义委托private delegate void shixudong_invoke(string invokefun);

复制代码 代码如下:

private void showstrs(string recv_strs)
        {
            if (recv_strs.length != 0)
            {
                if (this.invokerequired)
                {
                    shixudong_invoke invoke = new shixudong_invoke(showstrs);
                    this.invoke(invoke, (object)recv_strs);
                }
                else
                {
                    textbox1.text = recv_strs;

                }
            }

6、到此为止,服务端已经添加完毕

7,客户端代码,首先跟服务端一样,添加命名空间,在界面上添加button事件

复制代码 代码如下:

private void button1_click(object sender, eventargs e)
        {
            ipendpoint ipendpoint = new ipendpoint(ipaddress.parse("127.0.0.1"), 7878);//ip,端口号
            socket socket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
            socket.beginconnect(ipendpoint, new asynccallback(sending), socket);//回调方法sending
        }

8、添加回调方法,代码如下

复制代码 代码如下:

private void sending(iasyncresult rec_socket)
        {
            socket socket = (socket)rec_socket.asyncstate;
            try
            {
                if (socket.connected)
                {
                    byte[] msgbuff = encoding.utf8.getbytes(textbox1.text);
                    socket.send(msgbuff);
                    //socket.accept();
                }
                else
                {
                    console.writeline("error!", "error!");
                }
            }
            catch
            {
                console.writeline("error!", "error!");
            }

9、到此为止,客户端代码已经完成,调试的时候先启动服务端,然后启动客户端

10、运行截图如下,点击按钮前,在文本框中输入shixudong

.net的socket异步通讯示例分享