我的代码中有以下一个函数:
       /// <summary>
        /// 发送文本消息
        /// </summary>
        /// <param name="IP">目标IP</param>
        /// <param name="msg">消息内容</param>
        /// <returns>是否发送成功</returns>
        public static bool Send(IPAddress IP, string msg)
        {
            bool tag = false;
            _IPEP = new IPEndPoint(IP, _port);
            if (!_sendSocket.Connected)
            {
                _sendSocket.Connect(_IPEP);
            }
                if (_sendSocket.Connected)
                {
                    MessageBox.Show("Connection Successful!");
                    byte[] data = Encoding.ASCII.GetBytes(msg);
                    byte[] sizeinfo = new byte[4];
                    //could optionally call BitConverter.GetBytes(data.length);
                    sizeinfo[0] = (byte)data.Length;
                    sizeinfo[1] = (byte)(data.Length >> 8);
                    sizeinfo[2] = (byte)(data.Length >> 16);
                    sizeinfo[3] = (byte)(data.Length >> 24);
                    _sendSocket.Send(sizeinfo);
                    _sendSocket.Send(data);
                    tag = true;
                }
                else
                {
                    MessageBox.Show("Networks block!");
                    tag = false;
                }
            
            return tag;
        }当按send按钮,第一次调用的时候,是正常的,但第二次再调用的时候,运行到
                _sendSocket.Connect(_IPEP);
就报错了,说"a connect request was made on an already connected socket",
我是第一次写Socket,请大家帮忙看看,
谢谢了

解决方案 »

  1.   

    是不是没有关闭socket的原因:加上这句试试:_sendSocket.Send(sizeinfo);
    _sendSocket.Send(data);
    _sendSocket.Close();
      

  2.   

    if (_sendSocket != null && !_sendSocket.Connected)
                {
                    _sendSocket.Close();
                    _sendSocket = null;
                    _sendSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
                    _sendSocket.Connect(_IPEP);
                }
      

  3.   

    socket没有关闭!同意BearRui(AK-47) ( )
      

  4.   

    谢谢各位,现在程序不报错了
    但是我还是只能收到一条信息,以下是我的监听线程上的部分代码,我想应该是AcceptSocket();一次只能处理一个Socket的原因,如果我连续不停的发就应该把Accept放到一个循环里面吧,只是我不知道这个循环的条件应该是什么?还是要请教各位了!   
            try
                {
                    _tcpL = new TcpListener(Dns.Resolve(Dns.GetHostName()).AddressList[0], _port);
                    _tcpL.Start();
                        Socket socket = _tcpL.AcceptSocket();
                    if (socket.Connected)
                    {      
                         //读数据的操作
    }
      

  5.   

    直接
    while(true){
       Socket socket = _tcpL.AcceptSocket();
      if (socket.Connected)
        {
       //读数据的操作
      }
    }
      

  6.   

    新开线程用来接受消息.循环体可以设置个变量BOOL rot=true;,然后用
    while(rot)
    {
      /接收
    }
    这么来做.需要结束接收线程时,把rot = false就可以
      

  7.   

    你的程序是单线运行的,也就是说,连接以后就直接去接收数据,而没有回去监听,接受完数据以后,就直接关闭。这样当然不可以的。给你一个比较简单的参考。using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;// 客户端异步的对象
    public class StateObject {
        // 客户端
        public Socket workSocket = null;
        // 接收缓冲区大小
        public const int BufferSize = 1024;
        // 接收缓冲区
        public byte[] buffer = new byte[BufferSize];
    // 接收到的数据,放在一个StringBuilder里
        public StringBuilder sb = new StringBuilder();  
    }// 异步服务器类
    public class AsynchronousSocketListener {
        // 线程信号
        public static ManualResetEvent allDone = new ManualResetEvent(false);    public AsynchronousSocketListener() {
        }    public static void StartListening(int Port) {
            // 接收缓冲
            byte[] bytes = new Byte[1024];        // 定义终端
            
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port);        // 建立一个 TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp );        // 将Socket绑定终端
            try {
                listener.Bind(localEndPoint);
                listener.Listen(100); // 允许最多100个等待连接            while (true) {
                    // 设置同步信号
                    allDone.Reset();                // 开始异步监听
                    Console.WriteLine("等待连接...");
                    listener.BeginAccept( 
                        new AsyncCallback(AcceptCallback),
                        listener );                // 阻塞当前线程,直到有一个客户端连接上来,这时候,会自动调用AcceptCallback这个方法
                    allDone.WaitOne();
                }        } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }        Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
            
        }
    // 异步连接回调方法
        public static void AcceptCallback(IAsyncResult ar) {
            // 通知主线程可以继续接收连接了,从上面的allDone.WaitOne()这个地方继续运行
            allDone.Set();        // 获得客户端的Socket
            Socket listener = (Socket) ar.AsyncState;       // 服务端结束异步连接
            Socket handler = listener.EndAccept(ar);        // 建立一个状态对象
            StateObject state = new StateObject();
            state.workSocket = handler;
           // 开始客户端的异步接受数据
            handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }// 异步接收数据的回调方法
        public static void ReadCallback(IAsyncResult ar) {
            String content = String.Empty;
            
            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket handler = state.workSocket;        // 结束接收. 
            int bytesRead = handler.EndReceive(ar);        if (bytesRead > 0) {
                // 将当前所接收的存起来,继续接收,直到接收不到东西。
                state.sb.Append(Encoding.ASCII.GetString(
                    state.buffer,0,bytesRead));            // Check for end-of-file tag. If it is not there, read 
                // more data.
                content = state.sb.ToString();
                if (content.IndexOf("<EOF>") > -1) {
                    // All the data has been read from the 
                    // client. Display it on the console.
                    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                        content.Length, content );
                    // Echo the data back to the client.
                    Send(handler, content);
                } else {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
                }
            }
        }
        
        private static void Send(Socket handler, String data) {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);        // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }    private static void SendCallback(IAsyncResult ar) {
            try {
                // Retrieve the socket from the state object.
                Socket handler = (Socket) ar.AsyncState;            // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);            handler.Shutdown(SocketShutdown.Both);
                handler.Close();        } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
        public static int Main(String[] args) {
            StartListening();
            return 0;
        }
    }
      

  8.   

    Socket是一个可以说简单也可以说复杂的东西,也是网络通讯的基础。上面那个是微软给的简单的例子。性能好的架构会复杂得多,但是就算觉得很难懂,也要啃下来,没办法。
      

  9.   

    有点晕了,放到while(true)里面有点问题,就是信息重复了
    代码如下:      public static void ReadMessage()
            {
                bool tag = true;            try
                {
                    Notification noti = new Notification();
                    _tcpL = new TcpListener(Dns.Resolve(Dns.GetHostName()).AddressList[0], _port);
                    _tcpL.Start();
                    while(tag)
                    {      
                        Socket socket = _tcpL.AcceptSocket();
                        if (socket.Connected)
                        {
    ...
    //获得消息内容,保存在totalread里面
    ...
                    noti.Text = Encoding.ASCII.GetString(data, 0, totalread);
                    noti.Caption = "Message";
                    noti.Visible = true;                    }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }        }会有N个同样内容的Notification出现,怎么解决呢?有点头晕了,没睡午觉..
      

  10.   

    谢谢ezhuyin(碧海蓝天) ,不错的sample,
      

  11.   

    while(tag)
                    {      
                        Socket socket = _tcpL.AcceptSocket();
                        if (socket.Connected)
                        {
    ...
    //获得消息内容,保存在totalread里面
    ...
                    noti.Text = Encoding.ASCII.GetString(data, 0, totalread);
                    noti.Caption = "Message";
                    noti.Visible = true;                    }
                    }你这个是单用户连接模式,无法应付多用户连接。
    // 获得消息内容,保存在totalread里面,这里的代码才是关键的。是接收信息的代码。
    // 读数据如果你用同步,就使用Socket.Receive方法
    StringBuilder sb = new StringBuilder()
    byte[] buffer = new byte[1024]
    while (socket.Available>0)
    {
    socket.Receive(buffer);
    sb.Append(Encoding.ASCII.GetString(buffer);
    }
      

  12.   

    noti.Text = sb.ToString(); // 漏掉了
      

  13.   

    我也补上略去的代码,供交流我的程序是点对点发的,也需要多处理多用户吗?//获取信息,并保存
                   while(tag)
                    {      
                        Socket socket = _tcpL.AcceptSocket();
                        if (socket.Connected)
                        {                        byte[] sizeinfo = new byte[4];                        //read the size of the message
                            int totalread = 0, currentread = 0;                        currentread = totalread = socket.Receive(sizeinfo);                        while (totalread < sizeinfo.Length && currentread > 0)
                            {
                                currentread = socket.Receive(sizeinfo,
                                          totalread, //offset into the buffer
                                          sizeinfo.Length - totalread, //max amount to read
                                          SocketFlags.None);
                                totalread += currentread;
                            }                        int messagesize = 0;
                            messagesize |= sizeinfo[0];
                            messagesize |= (((int)sizeinfo[1]) << 8);
                            messagesize |= (((int)sizeinfo[2]) << 16);
                            messagesize |= (((int)sizeinfo[3]) << 24);                        byte[] data = new byte[messagesize];
                            totalread = 0;
                            currentread = totalread = socket.Receive(data,
                                         totalread, //offset into the buffer
                                        data.Length - totalread, //max amount to read
                                        SocketFlags.None);
                            while (totalread < messagesize && currentread > 0)
                            {
                                currentread = socket.Receive(data,
                                         totalread, //offset into the buffer
                                        data.Length - totalread, //max amount to read
                                        SocketFlags.None);
                                totalread += currentread;
                            }                noti.Text = Encoding.ASCII.GetString(data, 0, totalread);
                    noti.Caption = "Message";
                    noti.Visible = true;                    }
                    }
    我现在就是想没次有消息来的时候就显示出来,问题时While(true)里面让我重复的收到相同的消息
    去吃饭了,回头再来。多谢碧海蓝天^_^