C# 聊天程序



当我使用本地计算机托管并连接到它时,它可以 100% 工作,但当我实时尝试它时(服务器程序位于实际服务器上,客户端位于其他机器上(它不起作用。我收到"无法建立连接,因为目标计算机主动拒绝了它"。我检查了它是否在主动侦听(并且服务器上的端口太正确(-它是,禁用了包括路由器在内的所有防火墙[它还设置了一个规则,允许它在尝试禁用之外]-没有修复。

这可能是内部网络问题吗?就像它只是不喜欢尝试连接到本地机器一样?我一无所知,没有其他例外或任何东西。

服务器代码

IPAddress ip = IPAddress.Parse("127.0.0.1");
Int32 port = 9818;
TcpListener server = new TcpListener(ip,port);
TcpClient client;try
{
server.Start();
Console.WriteLine("Server Started..");

}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
while (true)
{
client = server.AcceptTcpClient();
byte[] recieveBuffer = new byte[100];
byte[] sendBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(recieveBuffer, 0, recieveBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach (byte b in recieveBuffer)
{
if (b.Equals(00))
{
break;
}
else
msg.Append(Convert.ToChar(b).ToString());
}
int byteCount = Encoding.ASCII.GetByteCount(msg.ToString());
byte[] sendData = new byte[byteCount];
stream.Write(sendData, 0, sendData.Length);
Console.WriteLine(msg);}//End while

而客户是..

public Int32 port = 9818;
public TcpClient client;
public string serverIP = "10.0.0.20";
//public string serverIP = "localhost"; //For testings
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient(serverIP, port);
//Clean up space
int byteCountU = Encoding.ASCII.GetByteCount(txtUser.Text);
int byteCountP = Encoding.ASCII.GetByteCount(txtPassword.Text);
//Send
byte[] sendDataU = new byte[byteCountU];
byte[] sendDataP = new byte[byteCountP];
//Greating should be formated on server's end to not ruin user and password sending
sendDataU = Encoding.ASCII.GetBytes(txtUser.Text);
sendDataP = Encoding.ASCII.GetBytes(txtPassword.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendDataU, 0, sendDataU.Length);
//Close
stream.Close();
client.Close();

抱歉,这个格式化界面是我能做的最好的

这是一个网络问题,而不是编程问题。

作为一般规则,网络类不关心另一端是否在同一台计算机上,同一交换机或旅行者2号探测器上。在那里开辟路径是网络问题,而不是编程问题。

我最好的猜测是像Windows Firefall这样的东西有点激进。

作为旁注:异常处理是我的烦恼,你的问题。以下是我经常链接的两篇关于主题的文章:

  • https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
  • https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

将服务器设置为仅在本地主机上侦听 (127.0.0.1(。这意味着只允许和解析本地连接,因此防火墙将在这些连接上被禁用,大多数时候您可以忽略它。当您调试应用程序或在同一台计算机上进行进程间通信时,它很有用。

要侦听来自其他计算机的传入连接,您应该有足够的权限并将服务器地址设置为 0.0.0.0,这意味着"侦听所有外部连接"。

最新更新