Can';t使用c#套接字接收字节
我正在尝试制作一个简单的聊天服务器。服务器接受来自客户端的连接,但没有接收任何字节,我对C#和OOP非常陌生,因此这可能与套接字完全无关,就在我的代码中,我尝试过使用C#查看套接字连接的示例,但由于缺乏知识,我无法将其实现到我的程序中Can';t使用c#套接字接收字节,c#,sockets,C#,Sockets,我正在尝试制作一个简单的聊天服务器。服务器接受来自客户端的连接,但没有接收任何字节,我对C#和OOP非常陌生,因此这可能与套接字完全无关,就在我的代码中,我尝试过使用C#查看套接字连接的示例,但由于缺乏知识,我无法将其实现到我的程序中 //server using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SocketLogger { class Progr
//server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketLogger
{
class Program
{
static void Main(string[] args)
{
startServer();
}
public static void startServer()
{
IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener listener = new TcpListener(IPaddr, 6969);
TcpClient client = default(TcpClient);
try
{
listener.Start();
Console.WriteLine("Server Has Started");
}
catch(Exception err)
{
Console.WriteLine("error:" + err);
}
while(true)
{
listener.AcceptTcpClient();
Console.WriteLine("Accepted Client");
byte[] buffer = new byte[1024];
client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
Console.WriteLine(message);
Console.Read();
}
}
}
}
为了在我的机器上测试你的代码,我不得不改变你向服务器提供IP地址的方式。这:
IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
使用IPv6地址设置IPaddr。在客户端代码中:
TcpClient client = new TcpClient("127.0.0.1", 6969);
为客户端提供IPv4地址。因此,我将服务器代码更改为:
// IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
IPAddress IPaddr = IPAddress.Parse("127.0.0.1");
转到下一个问题,服务器缺少客户端字节,因为正在执行两个AcceptTcpClient()。将代码更改为:
//listener.AcceptTcpClient();
byte[] buffer = new byte[1024];
client = listener.AcceptTcpClient();
Console.WriteLine("Accepted Client");
它将接收字符串。您确定您使用的端口是免费的吗?@StefanoCavion yep端口6969上没有运行任何内容,此外,如果是这种情况,客户机不会连接,但在我的情况下,客户机确实连接,但测试消息未发送,我不确定为什么不使用Localost或loopback 127.0.0.1,它们可能无法工作,具体取决于PC的配置。对于服务器,始终使用IPAddress.Any侦听。客户端应连接到PC IP地址或计算机名称。如今,大多数PC使用地址为零的IPV6(而不是IPV4),因此要获得IPV4地址,请使用地址1:IPAddress IPaddr=Dns.GetHostEntry(“localhost”).AddressList[0];不要忽略返回值——正如aamartin2k的回答中指出的那样,也不要忽略实际的客户机,因为您没有注意从
Read
读取的返回值——它告诉您实际得到了多少字节。您需要注意这一点,特别是因为不能保证它与另一端为任何特定的写入
调用提供的字节数相匹配。
//listener.AcceptTcpClient();
byte[] buffer = new byte[1024];
client = listener.AcceptTcpClient();
Console.WriteLine("Accepted Client");