【发布时间】:2014-08-29 00:58:02
【问题描述】:
我要做的是将数据(字符串或字节)从一台计算机简单地传输到另一台计算机。 我使用套接字作为远程计算机之间的链接。 我刚开始我的项目,但问题是我无法在计算机之间建立成功的连接。 我不明白 IPEndpoint 中需要什么 IP 地址,我的计算机 IPv4?我的路由器IP?我认为我的代码有问题。 它的目的是拥有 1 个客户端和 1 个服务器,之后我会将其开发为更大的应用程序,但现在我的代码是:
服务器:
class Server
{
static byte[] buffer;
static string data;
public static void StartListening()
{
while (true)
{
byte[] bytes = new Byte[100000];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[2];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress,16000);
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1000];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data != null)
{
Console.WriteLine(data);
break;
}
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
客户端:我尝试了 IPHostEntry 包含的所有三个 IP 地址,但它们也不起作用,我正在尝试使用笔记本电脑上的客户端程序。 代码:
public static void SendData(string send)
{
try
{
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("MyIPAddressThat in hostinfo Addresses[2]"), 16000);
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
byte[] msg = Encoding.ASCII.GetBytes(send);
sender.Send(msg);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
#region Catch
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
#endregion
}
我想让你关注的是计算机或调制解调器需要哪个 IP 地址,也许是我的程序无法运行的原因。 感谢一个帮助。
【问题讨论】:
-
+1 因为在没有评论的情况下投反对票并不好......