【问题标题】:Sending and recieving with TCP, using a socket more than once (C#)使用 TCP 发送和接收,多次使用套接字(C#)
【发布时间】:2017-05-22 04:10:41
【问题描述】:

编辑:原来我两次使用同一个端口。将这里留给任何谷歌搜索的人,像 htis 这样的线程过去曾帮助过我。

我目前正在做一个项目,我在服务器和客户端上有一个高分榜,两者同步数据,保存在 XML 中。我的一切正常工作,但我不断收到异常“System.Net.Sockets.SocketException:每个套接字地址只有一种用法”,我不知道如何摆脱它。对我来说,代码看起来不错,因为我在Update 中关闭了TcpClient,然后它才转到Recieve。谁能发现我错过了什么,或者向我解释我做错了什么?我对此很陌生,所以解释中的一些实际代码会有很大帮助!

static void Main(string[] args)
    {
        Update();
        Recieve();

    }

服务器发送给客户端:

public static void Update()
    {
        List<string> stringList = new List<string>();
        XmlDocument highScore = new XmlDocument();
        highScore.Load("hs.xml");
        for (int i = 0; i < 5; i++)
        {
            int placering = i + 1;
            stringList.Add(highScore.SelectSingleNode("highScores/score" + (placering)).InnerText);

        }
        string toSend = stringList[0] + stringList[1] + stringList[2] + stringList[3] + stringList[4];

        string adress = "127.0.0.1";
        int port = 82;
        TcpClient tcpClient = new TcpClient();

        tcpClient.Connect(adress, port);
        NetworkStream stream = tcpClient.GetStream();

        Byte[] bSend = Encoding.ASCII.GetBytes(toSend);
        NetworkStream tcpStream = tcpClient.GetStream();
        tcpStream.Write(bSend, 0, bSend.Length);
        tcpClient.Close();
    }

服务器从客户端接收:

public static void Recieve()
    {
        //skapa ett TcpListener objekt
        IPAddress myIp = IPAddress.Parse("127.0.0.1");
        TcpListener tcpListener;
        int port = 82;


        tcpListener = new TcpListener(myIp, port);
        tcpListener.Start();   //Throws the exception
        Socket socket = tcpListener.AcceptSocket();

        int messageSize;
        Byte[] bMessage = new Byte[256];


        while (true)
        {
            try
            {
                messageSize = socket.Receive(bMessage);
                break;
            }
            catch { }
        }

        //konvertera till string och skriv ut
        string message = "";
        for (int i = 0; i < messageSize; i++)
        {
            message += Convert.ToChar(bMessage[i]);
        }

        for (int i = 0; i < 5; i++)
        {
            SaveScore(int.Parse(message[i].ToString()), i + 1);
        }

        socket.Close();
    }

这两种方法都在同一个Program.cs中,而不是游戏中的一个单独的解决方案。

【问题讨论】:

  • 哪一行抛出异常?
  • tcpListener.Start() @apocalypse

标签: c# sockets tcp


【解决方案1】:

您还应该在您的 Receive 方法中停止您的 TcpListener,它是否可能在您的应用程序的先前运行中仍然处于打开状态?

【讨论】:

    【解决方案2】:

    原来这是一件简单的事情,在基本上重写了方法之后,我发现发送和接收的方法都使用端口 82 在我从不同的项目复制粘贴后......是的。感谢那些试图提供帮助的人,哈哈

    【讨论】:

      最近更新 更多