当前位置: 移动技术网 > IT编程>开发语言>c# > c# socket网络编程接收发送数据示例代码

c# socket网络编程接收发送数据示例代码

2019年07月18日  | 移动技术网IT编程  | 我要评论

代码分2块,server端:

复制代码 代码如下:

class program
    {
        static void main(string[] args)
        {
            tcplistener lsner = new tcplistener(9000);
            lsner.start();
            console.writeline("started in port: 9000");
            while (true)
            {
                tcpclient client=lsner.accepttcpclient();
                console.writeline("new client received. hashcode: {0}", client.gethashcode());
                threadpool.queueuserworkitem(new waitcallback(processtcpclient), client);
            }
            console.readkey();
        }

        private static void processtcpclient(object state)
        {
            tcpclient client=state as tcpclient;
            if(client==null)
                console.writeline("client is null");

            networkstream ns=client.getstream();
            streamwriter sw = new streamwriter(ns);
            sw.writeline("welcome.");
            sw.flush();
            sw.close();
            client.close();
        }

client端:

复制代码 代码如下:

class program
    {
        static void main(string[] args)
        {
            ipaddress address = ipaddress.parse("127.0.0.1");
            ipendpoint ep=new ipendpoint(address, 9000);
            tcpclient client = new tcpclient();
            client.connect(ep);
            networkstream ns=client.getstream();
            streamreader sr = new streamreader(ns);
            console.writeline(sr.readtoend());
            sr.close();
            sr.dispose();
            ns.close();
            ns.dispose();
            client.close();
            console.readkey();
        }
    }


 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网