如何使用C#插座连接两台高速PC
因此,我有下面列出的服务器-客户端通信代码,只要在同一台电脑上启动两个程序,它就可以正常工作,但如果我尝试连接两台不同的电脑,它就无法工作。有人知道我必须将ip放在何处吗?我向getter添加了一些Console.writeline,并将这些输出作为注释如何使用C#插座连接两台高速PC,c#,sockets,ip,C#,Sockets,Ip,因此,我有下面列出的服务器-客户端通信代码,只要在同一台电脑上启动两个程序,它就可以正常工作,但如果我尝试连接两台不同的电脑,它就无法工作。有人知道我必须将ip放在何处吗?我向getter添加了一些Console.writeline,并将这些输出作为注释 // ExecuteClient() Method static void ExecuteClient(string message) { try
// ExecuteClient() Method
static void ExecuteClient(string message)
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
Console.WriteLine(ipHost); //System.Net.IPHostEntry
IPAddress ipAddr = ipHost.AddressList[0];
Console.WriteLine(ipHost.AddressList.ToString()); //System.Net.IPAddress[]
Console.WriteLine(ipAddr); //gives back an ip v6 address
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
Console.WriteLine(localEndPoint);
// Creation TCP/IP Socket using
// Socket Class Costructor
Console.WriteLine("AddressFamily: " + ipAddr.AddressFamily.ToString()); //InterNetworkV6
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of messagge that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("<EOF> " + message);
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the messagge using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
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());
}
}
//ExecuteServer method
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true)
{
//Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
if(data == "<EOF> " + "kill")
{
Application.Exit();
} else if (data == "<EOF> " + "test")
{
Console.Writeline("It works!");
} else
{
byte[] message = Encoding.ASCII.GetBytes("Error 404 message not found!");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
Messagebox1();
}
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
}
}
//ExecuteClient()方法
静态void ExecuteClient(字符串消息)
{
尝试
{
//建立远程端点
//用于套接字。此示例
//在本地计算机上使用端口11111
//电脑。
IPHostEntry ipHost=Dns.GetHostEntry(Dns.GetHostName());
Console.WriteLine(ipHost);//System.Net.IPHostEntry
IPAddress ipAddr=ipHost.AddressList[0];
Console.WriteLine(ipHost.AddressList.ToString());//System.Net.IPAddress[]
Console.WriteLine(ipAddr);//返回ip v6地址
IPEndPoint localEndPoint=新的IPEndPoint(ipAddr,11111);
WriteLine(localEndPoint);
//使用创建TCP/IP套接字
//套接字类构造器
Console.WriteLine(“AddressFamily:+IPAddress.AddressFamily.ToString());//InterNetworkV6
套接字发送器=新套接字(ipAddr.AddressFamily,
流,ProtocolType.Tcp);
尝试
{
//将插座连接到遥控器
//使用方法Connect()的端点
sender.Connect(localEndPoint);
//我们打印端点信息
//我们是有联系的
WriteLine(“连接到->{0}的套接字”,
sender.RemoteEndPoint.ToString());
//创建消息
//我们将发送到服务器
byte[]messageSent=Encoding.ASCII.GetBytes(“+消息”);
int byteSent=sender.Send(messageSent);
//数据缓冲区
字节[]messageReceived=新字节[1024];
//我们使用
//方法Receive()。此
//方法返回字节数
//收到,我们将使用
//将它们转换为字符串
int byteRecv=sender.Receive(messageReceived);
WriteLine(“来自服务器的消息->{0}”,
Encoding.ASCII.GetString(messageReceived,
0,byteRecv);
//使用闭合插座
//方法Close()
发送器关闭(SocketShutdown.Both);
sender.Close();
}
//套接字异常的管理
捕集物(捕集物)
{
WriteLine(“ArgumentNullException:{0}”,ane.ToString());
}
捕获(SocketException se)
{
WriteLine(“SocketException:{0}”,se.ToString());
}
捕获(例外e)
{
WriteLine(“意外异常:{0}”,e.ToString());
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
//ExecuteServer方法
公共静态void ExecuteServer()
{
//建立本地端点
//对于socket.Dns.GetHostName
//返回主机的名称
//运行应用程序。
IPHostEntry ipHost=Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr=ipHost.AddressList[0];
IPEndPoint localEndPoint=新的IPEndPoint(ipAddr,11111);
//使用创建TCP/IP套接字
//套接字类构造器
套接字侦听器=新套接字(ipAddr.AddressFamily,
流,ProtocolType.Tcp);
尝试
{
//使用Bind()方法,我们将
//服务器套接字的网络地址
//将连接到此服务器的所有客户端
//服务器套接字必须知道此网络
//地址
Bind(localEndPoint);
//使用Listen()方法创建
//所需的客户端列表
//连接到服务器
听(10);
while(true)
{
//Console.WriteLine(“等待连接…”);
//等待时暂停
//传入连接使用
//服务器上的Accept()方法
//将接受客户端的连接
套接字clientSocket=listener.Accept();
//数据缓冲区
字节[]字节=新字节[1024];
字符串数据=null;
while(true)
{
int numByte=clientSocket.Receive(字节);
data+=Encoding.ASCII.GetString(字节,
0,numByte);
if(data.IndexOf(“”>-1)
打破
}
WriteLine(“接收到的文本->{0}”,数据);
如果(数据==“+”终止)
{
Application.Exit();
}else if(数据==“”+“测试”)
{
孔索
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.clientSocket.Connect(new IPEndPoint(System.Net.IPAddress.Parse(ip), int.Parse(port)));