gpt4 book ai didi

c# - 为什么我的客户端/服务器代码不能在我的本地机器之外工作?

转载 作者:可可西里 更新时间:2023-11-01 02:49:55 24 4
gpt4 key购买 nike

我正在尝试创建一个非常基本的小型客户端服务器应用程序,但我只能让它在我自己的机器上本地运行。

服务器代码:

        int d = 0;
try
{
for (AdministratorPort = 8000; d < 1; AdministratorPort++)
{
IPAddress ipAddress = IPAddress.Parse("220.101.27.107");

TcpListener tcpListener = new TcpListener(ipAddress, AdministratorPort);
tcpListener.Start();

// Display results.
Label label = new Label();

label.Text = "The server is connected to, and running on Port: 8001." + Environment.NewLine +
tcpListener.LocalEndpoint + Environment.NewLine +
"Team Share Server is now awaiting new connections.";

label.AutoSize = true;
label.Location = new Point(4, 15);
panel.Controls.Add(label);

panel.AutoScroll = true;

Socket socket = tcpListener.AcceptSocket();
label.Text += Environment.NewLine +
"Connection accepted from: " + socket.RemoteEndPoint;

byte[] Message = new byte[100];

int k = socket.Receive(Message);
label.Text += Environment.NewLine +
"Message received from server.";

for(int i = 0; i < k; i++)
label.Text += Environment.NewLine +
Convert.ToChar(Message[i]);

ASCIIEncoding asciiEncoding = new ASCIIEncoding();
socket.Send(asciiEncoding.GetBytes("The string was received by the server."));

label.Text += Environment.NewLine +
"Acknowledgement sent to client.";

socket.Close(10);
tcpListener.Stop();
d = 1;
}
}
catch (Exception e) {
d = 0;
File.WriteAllText("this.txt", e.StackTrace);
}

客户端代码:

        int d = 0;
try
{
for (int port = 8000; d < 1; port++)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("TRYING to connect...");

tcpclnt.Connect("220.101.27.107", port); // use the ipaddress as in the server program

Console.WriteLine("Connected, finally.");
Console.Write("Enter the string to be transmitted : ");

String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();

ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");

stm.Write(ba, 0, ba.Length);

byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);

for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));

tcpclnt.Close();
d = 1;
}
}

catch (Exception e)
{
d = 0;
Console.Write("oh no..... " + e.StackTrace + " " + e.Data + " " + e.Message.ToString());
Console.Read();
}

我做错了什么?

编辑:我得到的错误是“连接超时 cos 主机没有响应”或者大多数时候我得到“主机主动拒绝连接”,最近的错误是:“连接尝试失败,因为连接方在连接后没有正确响应一段时间,或建立的连接失败,因为连接的主机未能响应 220.101.27.107”。

最佳答案

你试过解锁端口吗?

关于c# - 为什么我的客户端/服务器代码不能在我的本地机器之外工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1674923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com