using Community; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Model { /// /// 通讯类 /// public class RobotSocket : NotificationObject { #region 通讯套接字 /// /// 通讯套接字 /// public Socket MySocket { get; set; } #endregion #region 通讯连接IP /// /// 通讯连接IP /// private string CommunicationIP { get; set; } #endregion #region 通讯连接端口号 /// /// 通讯连接端口号 /// private int CommunicationPort { get; set; } #endregion #region 连接状态 private ShowInfo connStatu; /// /// 连接状态 /// public ShowInfo ConnStatu { get { return connStatu; } set { connStatu = value; this.RaisePropertyChanged("ConnStatu"); } } #endregion #region 构造函数 /// /// 构造函数 /// /// 连接IP /// 端口号 public RobotSocket(string ip, int port) { CommunicationIP = ip; CommunicationPort = port; ConnStatu = new ShowInfo(); ConnStatu.StatuInfo = "等待连接"; } #endregion #region 开启连接 /// /// 开启连接 /// /// 套接字对象 /// IP地址 /// 端口 public void StartConn() { try { //1.创建监听套接字 使用ip4协议 流式传输 tcp连接 MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 获取服务器端口 IPAddress address = IPAddress.Parse(CommunicationIP); IPEndPoint endpoint = new IPEndPoint(address, CommunicationPort); //开启连接服务器 MySocket.Connect(endpoint); } catch { } } #endregion #region 关闭连接 /// /// 关闭连接 /// public void ShutDown() { try { MySocket.Close(); //关闭套接字 } catch (Exception) { } } #endregion #region 发送消息 byte[] sendbyte { get; set; } private static object sendLock = new Object(); /// /// 发送消息 /// public void Send(string strMgs) { try { lock (sendLock) { if (!string.IsNullOrEmpty(strMgs)) { //发送操作指令 sendbyte = System.Text.Encoding.ASCII.GetBytes(strMgs); //sendbyte = System.Text.Encoding.Default.GetBytes(strMgs); if (MySocket != null) { MySocket.Send(sendbyte); } } } } catch (Exception) { } } #endregion #region 接收消息 byte[] Message { get; set; } int lenght { get; set; } /// /// 接收消息A /// public string ReceivesMessageA() { Message = new byte[1024 * 1024 * 1]; //1.1创建消息缓存容器 lenght = MySocket.Receive(Message); //1.2接收的消息并存入缓存区,注意Receive也会阻断当前线程 // TheReceives = System.Text.Encoding.ASCII.GetString(Message, 0, lenght); TheReceives = System.Text.Encoding.UTF8.GetString(Message); return TheReceives; } /// /// 接收消息B /// /// public string ReceivesMessageB() { Message = new byte[1024 * 1024 * 1]; //1.1创建消息缓存容器 MySocket.Receive(Message); //1.2接收的消息并存入缓存区,注意Receive也会阻断当前线程 TheReceives = System.Text.Encoding.UTF8.GetString(Message); //TheReceives = System.Text.Encoding.ASCII.GetString(Message, 0, lenght); return TheReceives; } #endregion #region 接收到的信息 private string theReceives; /// /// 接收到的信息 /// public string TheReceives { get { return theReceives; } set { theReceives = value; this.RaisePropertyChanged("TheReceives"); } } #endregion } }