【发布时间】: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