我是套接字编程C#的新手。我试图在两台计算机之间建立聊天服务器,但我无法做到这一点,因为我无法启动我的Socket .....我给了服务器程序我的IP地址,但给了我一个例外......“请求的地址是在其上下文中无效“......这是代码:
IPAddress hostIPAddress = IPAddress.Parse("178.189.27.85");
TcpListener serverSocket = new TcpListener(hostIPAddress, 8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
客户端程序
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.128.1",8888);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
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();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
答案 0 :(得分:0)
IPAddress hostIPAddress = IPAddress.Parse("178.189.27.85");
您的计算机实际上是否在公共互联网上?我希望你的电脑有私人IP(例如192.168.x.y,172.16-32.x.y,10.x.y.z),除非它直接连接到你的网络连接。
假设您使用的是Windows,请使用命令提示符并运行ipconfig
,或访问“控制面板”并查找您的网络设置。例如,在Windows 7上,它位于“更改适配器设置”下的“网络和共享中心”中;查找活动适配器,右键单击并选择“状态”。
找到本地IP地址后,请使用该地址。或者您可以使用0.0.0.0作为通配符地址 - 实际上是说“只需接受来自任何地方的连接,我不关心我的IP地址是什么。”