asp.net socket多线程 简单监听端口,获得数据

来源:互联网 发布:上海淘宝网店转让信息 编辑:程序博客网 时间:2024/06/05 16:59

经过对上一篇文章,代码的二次开发得到了线面的这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public void CreatSocket()
    {
        try
        {
            int port = 2000;
            string host = "127.0.0.1";
 
            /**/
            ///创建终结点(EndPoint)
            IPAddress ip = IPAddress.Parse(host);//把ip地址字符串转换为IPAddress类型的实例
            IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例
 
            /**/
            ///创建socket并开始监听
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket对像,如果用udp协议,则要用SocketType.Dgram类型的套接字
            s.Bind(ipe);//绑定EndPoint对像(2000端口和ip地址)
            s.Listen(0);//开始监听
            Console.WriteLine("等待客户端连接");
 
            /**/
            ///接受到client连接,为此连接建立新的socket,并接受信息
 
            while (true)//定义循环,以便可以简历N次连接
            {
                Socket temp = s.Accept();//为新建连接创建新的socket
                //Console.WriteLine("建立连接");
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                DBHelper.ExecutCommand("INSERT INTO [ShuJu]([strs_VAR]) VALUES('" + recvStr + "')");//存入数据库
                if (temp != null)
                    temp.Close();
 
            }
 
            /**/
            ///给client端返回信息
            //Console.WriteLine("server get message:{0}", recvStr);//把客户端传来的信息显示出来
            //string sendStr = "ok!Client send message successful!";
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            //temp.Send(bs, bs.Length, 0);//返回信息给客户端
            //temp.Close();
            s.Close();
            //Console.ReadLine();
        }
        catch (Exception ex)
        {
            string s = ex.ToString();
        }
    }

然后,我们定义在一个网站,中定义监听(Global.asax)

1
2
3
4
5
void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        (new System.Threading.Thread(new System.Threading.ThreadStart(new Class1().CreatSocket))).Start();//开辟一个新线程
     }

这样就可以啦!可以接受N次的连接啦!

o(∩_∩)o

0 0
原创粉丝点击