C# TCP-我可以';作为服务器进行侦听时不发送数据
通过TCP侦听时无法发送数据。我需要一直侦听传入的连接,并在需要时发送一些数据。当程序加载时,我的服务器代码开始侦听,但当我尝试发送数据时,会出现以下错误: “每个套接字地址(协议/网络地址/端口)通常只允许使用一次(通常在负载情况下)。” 这是我的代码:C# TCP-我可以';作为服务器进行侦听时不发送数据,c#,.net,sockets,tcp,socketexception,C#,.net,Sockets,Tcp,Socketexception,通过TCP侦听时无法发送数据。我需要一直侦听传入的连接,并在需要时发送一些数据。当程序加载时,我的服务器代码开始侦听,但当我尝试发送数据时,会出现以下错误: “每个套接字地址(协议/网络地址/端口)通常只允许使用一次(通常在负载情况下)。” 这是我的代码: public void Send(object sender, System.EventArgs e) { String str = "08"; String str2 = "4213";
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);
}
});
将通知您任何帮助。异常会告诉您正在尝试多次打开同一服务器套接字。您应该在表单关闭时关闭
TcpListener
(并加入侦听线程)。您还可以使用单例服务来管理tcp侦听器(或分配一个静态字段,仅在未设置字段的情况下创建侦听器)。能否显示“尝试发送数据”的代码?问题中的代码只显示了发送消息和侦听某些数据的方法,实际使用的Connect()在哪里?您没有说明引发异常的位置,是在Connect()方法中还是在CreateServer()方法中?旁注:请注意,TCP是一个字节流(在每个方向上),而不是消息传递。无法保证从调用Read
得到的结果会与另一端调用Write
得到的结果1-1匹配。我现在添加了它。它在createrServer()tcp.start()语句中抛出异常客户端部分和服务器部分应该在不同的应用程序中。因此,服务器部分必须是与客户端部分分开的exe文件。您尝试打开两次应用程序。因此,再次创建服务器。