【发布时间】:2020-08-20 11:52:27
【问题描述】:
我正在尝试制作一个简单的聊天服务器。服务器接受来自客户端的连接,但没有收到任何字节,我对 C# 和 OOP 很陌生,所以这可能与套接字完全无关,只是在我的代码中,我尝试查看示例与 c# 的套接字连接,但由于缺乏知识,我无法将其实现到我的程序中。
//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();
}
}
}
}
//client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ClientConnect
{
class Program
{
static void Main(string[] args)
{
startClientConnection();
}
public static void startClientConnection()
{
string testString = "hello";
TcpClient client = new TcpClient("127.0.0.1", 6969);
//the teststring is for testing purposes
int SentBytes = Encoding.ASCII.GetByteCount(testString);
byte[] sendBuffer = new byte[SentBytes];
sendBuffer = Encoding.ASCII.GetBytes(testString);
NetworkStream stream = client.GetStream();
stream.Write(sendBuffer, 0, sendBuffer.Length);
stream.Close();
client.Close();
Console.Read();
}
}
}
【问题讨论】:
-
你确定你使用的端口是免费的吗?
-
@StefanoCavion 是的,端口 6969 上没有运行任何东西,如果是这种情况,客户端无法连接,但在我的情况下,客户端确实连接但没有发送测试消息,我我不知道为什么
-
请勿使用 Localost 或回送 127.0.0.1,它们可能无法正常工作,具体取决于 PC 的配置方式。对于服务器,始终使用 IPAddress.Any 进行侦听。客户端应连接到 PC IP 地址或计算机名称。如今,大多数 PC 使用地址为零的 IPV6(不是 IPV4),因此要获得 IPV4 使用地址 1:IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
-
不要忽略返回值 - 以及错过 aamartin2k 的回答中指出的实际客户端,你没有注意来自
Read的返回值 - 它告诉你 你实际得到了多少字节。您需要注意这一点,尤其是因为不能保证它会与对方提供给任何特定Write调用的字节数相匹配。