1.购买云服务器,云服务器会分配给用户一个公网IP,和自动分配的内网IP,可在服务器管理配置中查看。
2.在云服务器上开发UDP或TCP地址和端口,这样做目的是使防火墙允许客户端的地址访问云服务器,否则不能通信。
如腾讯云:在轻量应用服务器-》服务器-》防火墙-》添加规则
添加应用类型为自定义,IP来源为客户端地址IP(如任何类型),协议规则为UDP,端口为服务器接收端口即客户端要发送数据到云服务器的端口,策略为允许。
3.服务器端使用云服务器上的内网IP创建Socket套接字(UDP或TCP协议),客户端连接和发送均使用云服务器的公网IP。
UDP实例
客户端
public class UDPClient
{
private static Socket udpClient;
public static EndPoint severEndPoint = new IPEndPoint(IPAddress.Parse("云服务器公网IP"), 60000);
public void CreateUDPClient()
{
//1,创建socket
udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//2,绑定ip跟端口号
udpClient.Bind(new IPEndPoint(IPAddress.Any, 60001));
//3,接收数据
new Thread(ReceiveMessage) { IsBackground = true }.Start();
Console.WriteLine("服务器启动...");
}
public void SendInfo(string content)
{
byte[] data = Encoding.UTF8.GetBytes(content);
udpClient.SendTo(data, severEndPoint);
}
void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpClient.ReceiveFrom(data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
string message = Encoding.UTF8.GetString(data, 0, length);
MessageBox.Show("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
}
}
}
服务器
public class UDPServer
{
private static Socket udpServer;
public EndPoint clientPoint;
public void CreateUDPServer()
{
try
{
//1,创建socket
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//2,绑定ip跟端口号
udpServer.Bind(new IPEndPoint(IPAddress.Parse("云服务器内网IP"), 60000));
//3,接收数据
new Thread(ReceiveMessage) { IsBackground = true }.Start();
MessageBox.Show("服务器启动...");
}
catch(Exception ee)
{
MessageBox.Show(ee.ToString());
}
}
public void SendInfo(EndPoint client)
{
try
{
udpServer.SendTo(new byte[] { 0x11, 0x22 }, client);
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
}
public void SendInfo(string content)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(content);
udpServer.SendTo(data, clientPoint);
}
catch(Exception ee)
{
MessageBox.Show(ee.ToString());
}
}
void ReceiveMessage()
{
try
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
string message = Encoding.UTF8.GetString(data, 0, length);
SendInfo(remoteEndPoint);
clientPoint = remoteEndPoint;
MessageBox.Show("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
}
}
catch(Exception ee)
{
MessageBox.Show(ee.ToString());
}
}
}