using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace CommandMange.Socket
{
public class UdpOperater
{
/// <summary>
/// 单例模式
/// </summary>
public static UdpOperater Instance;
public static UdpOperater GetInstance(int clientPort, int serverPort, string serverIP)
{
if (Instance == null)
{
Instance = new UdpOperater(clientPort, serverPort, serverIP);
}
return Instance;
}
UdpClient udpClient = null;
IPEndPoint udpRemote = null;
UdpClient udpReceiver = null;
IPEndPoint remoteHost = null;
public UdpOperater(int clientPort, int serverPort, string serverIP)
{
udpClient = new UdpClient(clientPort);//客户端端口号
udpRemote = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);//服务端端IP
udpReceiver = new UdpClient(serverPort, AddressFamily.InterNetwork);//服务端端口号
remoteHost = null;
}
/// <summary>
/// 客户端
/// </summary>
public void ClientSend(string msg)
{
var data = Encoding.Default.GetBytes(msg);
udpClient.Send(data, data.Length, udpRemote);
}
/// <summary>
/// 服务端
/// </summary>
public string ServerReceive()
{
var data = udpReceiver.Receive(ref remoteHost);
return Encoding.Default.GetString(data);
}
}
}
UdpOperater udpOperater = UdpOperater.GetInstance(8110, 8112, "192.168.18.19");
txtMessage.Text += udpOperater.ServerReceive();