【发布时间】:2017-06-03 19:35:18
【问题描述】:
当我通过 TCP 监听时无法发送数据。我需要一直监听传入的连接,并且我应该在需要时发送一些数据。我的服务器代码在程序加载时开始监听,但是当我尝试发送数据时它给出了这个错误:
“每个套接字地址(协议/网络地址/端口)通常只允许使用一次(通常在负载下)。”
这是我的代码:
public void Send(object sender, System.EventArgs e)
{
String str = "08";
String str2 = "4213";
String CRCvalue = CRC("08" + str2);
String str3 = str2 + CRCvalue;
Connect("localhost", "hello localhost " + Guid.NewGuid());
}
static void Connect(String server, String message)
{
try
{
Int32 port = 2101;
TcpClient client = new TcpClient(server, port);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
System.Diagnostics.Debug.WriteLine("Sent");
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
System.Diagnostics.Debug.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
System.Diagnostics.Debug.WriteLine("SocketException: {0}", e);
}}
protected override void OnLoad(EventArgs e)
{
CreateServer();
}
private static void CreateServer()
{
var tcp = new TcpListener(System.Net.IPAddress.Any,25565);
tcp.Start();
var listeningThread = new Thread(() =>
{
while (true)
{
var tcpClient = tcp.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(param =>
{
NetworkStream stream = tcpClient.GetStream();
string incomming;
byte[] bytes = new byte[1024];
int i = stream.Read(bytes, 0, bytes.Length);
incomming = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
System.Diagnostics.Debug.WriteLine(incomming);
tcpClient.Close();
}, null);
}
});
我们将不胜感激。
【问题讨论】:
-
你能显示你“尝试发送数据”的代码吗?您在问题中的代码仅显示了发送消息和侦听某些数据的方法, Connect() 实际使用在哪里?你没有说明异常是在哪里抛出的,是在Connect()方法中还是在CreateServer()方法中?
-
旁注:注意 TCP 是字节流(在每个方向上),而不是消息传递。无法保证您从调用
Read获得的内容将与另一端调用Write进行 1-1 匹配。 -
我现在添加了。
-
并在 createrServer() tcp.start() 语句中抛出异常
-
客户端部分和服务器部分应该在不同的应用程序中。因此服务器部分必须是与客户端部分分开的 exe 文件。您尝试打开两次您的应用程序。所以服务器会再创建一次。
标签: c# .net sockets tcp socketexception