由于套接字没有连接并且没有提供地址,发送或接收数据的请求没有被接受?

服务器往客户端发送消息的时候报这个错:
错误定在://异步发送消息请求
server_socket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, new System.AsyncCallback(SendToServer), server_socket);

但是这是我按着客户端发消息的代码一点点改的不应该有错啊,百思不得原因,希望大佬助我!!!

贴上代码:

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;

public class ServerScript : MonoBehaviour
{
    //收到消息后的委托回调
    public delegate void ReceiveCallBack(string content);
    private string receive_str;
    Socket server;
    string msg = "";
    //服务器端收到消息的存储空间
    byte[] ReceiveBuffer = new byte[1024];
    //服务器收到消息后的回调委托
    private ReceiveCallBack callback;
    private Socket server_socket;

    private readonly object locker = new object();
    // Use this for initialization
    void Start()
    {
        //初始化服务器
        InitServer((string content) => {
            receive_str = content;
        });
    }

    //初始化服务器信息
    public void InitServer(ReceiveCallBack cb)
    {
        this.callback = cb;
        // 1.
         server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        // 2.
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 5001);
        // 3.
        server_socket.Bind(endPoint);
        // 4.
        server_socket.Listen(10);
        // 5.开始异步等待客户端的请求链接
        server_socket.BeginAccept(new System.AsyncCallback(Accept), server_socket);

        this.callback("开启服务器" + endPoint.ToString());
    }

    void OnGUI()
    {
        if (receive_str != null)
        {
            GUILayout.Label(receive_str);
        }
        msg = GUI.TextField(new Rect(0, 0, 500, 40), msg);
        if (GUI.Button(new Rect(0, 50, 100, 30), "Send"))
        {
            SendMessage(msg);
        }
    }
    //接受到客户端的链接请求后的回调函数
    void Accept(System.IAsyncResult ar)
    {
        //获取正在工作的Socket对象 
        Socket socket = ar.AsyncState as Socket;
        //存储异步操作的信息,以及用户自定义的数据  
        Socket worker = socket.EndAccept(ar);
        SocketError error;
        //开始异步接收客户端发送消息内容
        worker.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new System.AsyncCallback(Receive), worker);
        //继续异步等待新的客户端链接请求
        socket.BeginAccept(new System.AsyncCallback(Accept), socket);
    }
    //服务端收到客户端的消息后的回调函数
    void Receive(System.IAsyncResult ar)
    {
            //获取正在工作的Socket对象
            Socket worker = ar.AsyncState as Socket;
            int ByteRead = 0;
            try
            {
                ByteRead = worker.EndReceive(ar);
            }
            catch (System.Exception ex)
            {
                this.callback(ex.ToString());
            }
            if (ByteRead > 0)
            {
                string Content = Encoding.Default.GetString(ReceiveBuffer);
                this.callback(Content);
            }
            //继续异步等待客户端的发送消息请求
            worker.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new System.AsyncCallback(Receive), worker);
    }
    public void SendMessage(string message)
    {
        if (message == null)
            return;

        message += "\r\n";
        byte[] sendData = Encoding.UTF8.GetBytes(message);
        //异步发送消息请求
        server_socket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, new System.AsyncCallback(SendToServer), server_socket);
    }
    //发送消息结束的回调函数
    void SendToServer(System.IAsyncResult ar)
    {
        Socket worker = ar.AsyncState as Socket;
        worker.EndSend(ar);
    }
}

图片说明

c#

2个回答

这行有问题,服务器发送数据时要使用持有的客户端socket对象来发送

server_socket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, new System.AsyncCallback(SendToServer), server_socket);

改为:

worker.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, new System.AsyncCallback(SendToServer), worker);

没客户端连接,就向客户端发送消息或客户端断开导致的

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐