这两天自学socket通信  异步通信看的一头雾水,希望来个大神给讲讲,或者给一个详细的例子(最好有详细注释的)...自己照网上的实例做了一个只能发送,不能接受(接受时只能监听成功) 收不到数据有例子可以发邮箱:[email protected]  谢谢了

解决方案 »

  1.   

    我也刚学习,前几天看了一个例子,如下,希望对你有帮助吧!using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace server
    {
        class Program
        {        
            public static TcpListener myList;
            public static Socket s;               
            static void Main(string[] args)
            {
                try
                {
                    // 把IP地址转换为IPAddress的实例                      先得主机名再得IP
                    IPAddress ipAd = IPAddress.Parse(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString());
                    // 初始化监听器, 端口为8001
                    myList = new TcpListener(ipAd, 8001);
                    // 开始监听服务器端口
                    myList.Start();
                    // 输出服务器启动信息
                    Console.WriteLine("在8001端口启动服务...");
                    Console.WriteLine("本地节点为:" + myList.LocalEndpoint);
                    Console.WriteLine("等待连接.....");
                    while (true)
                    {
                        // 等待处理接入连接请求
                        // 新建立的连接用套接字s表示                  
                        s = myList.AcceptSocket();
                        //AcceptSocket 是一个阻塞方法,它返回可用来发送和接收数据的 Socket。如果希望避免阻塞,您可以使用 Pending 方法来确定传入连接队列中是否有连接请求。
                        //这里用一个新的类来接收s,在类里起一个thread处理 
                        AcceptSocketClass accept = new AcceptSocketClass(s); 
                        accept.StartThread();                                 
                    }
                    // 善后工作,释放资源
                    //s.Close();
                    //myList.Stop();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                }
                Console.ReadLine();
            }       
        }
        public class AcceptSocketClass
        {
            public static int times = 0;                        // 注意这里必须是静态变量(也就是类变量)才能在不同实例中更新它。
            Socket socket; 
            public AcceptSocketClass(Socket s) 
            { 
                socket = s; 
            } 
            public void StartThread() 
            { 
                //这个类起一个线程处理你的事件 
                Console.WriteLine("\n连接来自 " + socket.RemoteEndPoint);
                // 接收客户端信息
                byte[] b = new byte[100];
                int k = socket.Receive(b);           
                if (k > 0)
                {
                    Console.WriteLine("收到第{0}批数据流...",times+1);
                    for (int i = 0; i < k; i++)
                    {
                        Console.Write(Convert.ToChar(b[i]));
                    }
                    Thread td = new Thread(new ParameterizedThreadStart(DoAction));
                    td.Start(times);
                    times++;
                }              
            } 
            private void DoAction(object t) 
            { 
                Console.WriteLine("启动第{0}个线程",(int)t+1);
                Thread.Sleep(10000);
                Console.WriteLine("第{0}个线程醒了", (int)t + 1);
                // 处理客户端请求,给客户端回应
                ASCIIEncoding asen = new ASCIIEncoding();
                socket.Send(asen.GetBytes("The" + ((int)t + 1).ToString() + "th string was Echoed by the server."));
                Console.WriteLine("\n第{0}个线程已发送回应信息",(int)t+1);
                Thread.CurrentThread.Abort();//干完就退
            } 
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace client
    {
        class Program
        {
            public static int t = 1;
            public static string strHost = "192.168.1.1";//直接用本机IP省事
            public static string str;
            static void Main(string[] args)
            {
                try
                {
                    Thread[] myTd = new Thread[100];
                    for(int j=0;j<100;j++)
                    {
                        myTd[j] = new Thread(new ThreadStart(ConstantSend)); 
                        myTd[j].Start();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                }
                Console.ReadLine();
            }
            private static void ConstantSend()//收发在一个线程才能保证端口不错乱
            {
                try
                {
                    // 新建客户端套接字
                    TcpClient tcpclnt = new TcpClient();
                    Console.Write("连接----->");
                    // 连接服务器的8001端口,自己不一定用8001端口
                    tcpclnt.Connect(strHost, 8001);
                    Console.WriteLine("第{0}个连接成功", t);
                    t++;
                    Console.WriteLine("发送一个'Hi'过去后睡2000ms\n");                 // 得到客户端的流
                    Stream stm = tcpclnt.GetStream();
                    ASCIIEncoding asen = new ASCIIEncoding();
                    str = "Hi" + (t-1).ToString();
                    byte[] ba = asen.GetBytes(str);
                    //Console.WriteLine("传输中.....");
                    stm.Write(ba, 0, ba.Length);
                    Thread.Sleep(2000);
                    // 接收从服务器返回的信息
                    byte[] bb = new byte[100];
                    int k = stm.Read(bb, 0, 100);
                    // 输出服务器返回信息
                    for (int i = 0; i < k; i++)
                    {
                        Console.Write(Convert.ToChar(bb[i]));
                    }
                    Console.WriteLine();//空行区分下
                    // 关闭客户端连接
                    tcpclnt.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                }
            }
        }
    }
      

  2.   


    首先你监听程序是不是接收到一个Socket,然后如下:
    Socket socket = 接收到的Socket
                int iLen = 1024;
                string sRec = string.Empty;
                try
                {
                    while (iLen == 1024)
                    {
                        byte[] buffer = new byte[iLen];
                        iLen = socket.Receive(buffer);
                        sRec += Encoding.Default.GetString(buffer, 0, iLen);
                    }
                }
                catch(Exception ex)
                {
                }
      

  3.   

    谢谢哈!我懂了,我的监听没有设置while循环,在监听到客户端请求的时候就停止了
      

  4.   


    作为一个同样刚学socket的新手,亲测可用