我要做的是将数据(字符串或字节)从一台计算机简单传输到另一台计算机。 我使用套接字作为远程计算机之间的链接。 我在开始我的项目,但问题是我无法在计算机之间建立成功的连接。 我不明白什么IP地址需要在IPEndpoint,我的电脑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());
}
}
}
}
客户:我尝试了所有三个IP地址该IPHostEntry包含,他们也没有工作,即时通讯从我的笔记本电脑尝试客户端程序。 代码:
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,因为给不加评论了反对票是不是很好... – Kristof 2014-08-28 09:20:16