【发布时间】:2010-12-13 02:15:15
【问题描述】:
我正在尝试创建一个非常基本的小型客户端服务器应用程序,但我只能让它在我自己的机器上本地工作。
服务器代码:
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();
}
我做错了什么?
编辑: 我得到的错误是“连接超时,因为主机没有响应”或者大多数时候我得到“主机主动拒绝连接”,最近的错误是:“连接尝试失败,因为连接方在一段时间,或建立连接失败,因为连接的主机未能响应 220.101.27.107"。
【问题讨论】: