using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Reflection;
using System.Threading;
using Newtonsoft.Json;
namespace Test服务端
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public class SendJson
{
public string op { get; set; }
private Dictionary<string, object> _monitor = null;
public Dictionary<string, object> monitor
{
get
{
if (_monitor == null)
{
_monitor = new Dictionary<string, object>();
}
return _monitor;
}
set
{
this._monitor = value;
}
}
}
public Socket MySocket_listen;
public IPEndPoint MyIPEndPoint;
public Socket MySocket_server;
public Socket MySocket_send;
public void Listen()
{
MySocket_listen = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddress IP = IPAddress.Parse("192.168.253.3");
MyIPEndPoint = new IPEndPoint(IP,8888);
MySocket_listen.Bind(MyIPEndPoint);
MySocket_listen.Listen(10);
MySocket_listen.BeginAccept(new AsyncCallback(OnResquest), MySocket_listen);
}
public void OnResquest(IAsyncResult ar)
{
MySocket_server = (Socket)ar.AsyncState;
MySocket_send = MySocket_server.EndAccept(ar);
byte[] MyByte=new byte[1024];
string MyData = "{\"op\":\"UpdateDeviceStatus\",\"monitor\":{\"Fire\":\"false\",\"Smoke\":\"false\"}}";
MyByte = Encoding.UTF8.GetBytes(MyData);
MySocket_send.Send(MyByte,MyByte.Length,0);
MySocket_server.BeginAccept(new AsyncCallback(OnResquest),MySocket_server);
while(true)
{
byte[] Mybyte=new byte[1024];
int Mylength = MySocket_send.Receive(Mybyte);
string MyGetdata = Encoding.UTF8.GetString(Mybyte,0,Mylength);
MessageBox.Show("客户端发来数据:"+MyGetdata);
}
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
SendJson MySendJson = new SendJson();
MySendJson.op = "UpdateDeviceStatus";
MySendJson.monitor.Add("Fire", "false");
MySendJson.monitor.Add("Smoke", "false");
byte[] MyByte = new byte[1024];
//string MyData = txtData.Text.ToString();
string MyData = JsonConvert.SerializeObject(MySendJson);
MyByte = Encoding.UTF8.GetBytes(MyData);
MySocket_send.Send(MyByte, MyByte.Length, 0);
}
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
ThreadStart MyThreadStart = new ThreadStart(Listen);
Thread MyThread = new Thread(MyThreadStart);
if (btnOpen.Content.ToString() == "开始服务")
{
MyThread.Start();
btnOpen.Content = "停止服务";
}
else
{
MyThread.Interrupt();
MyThread.Abort();
btnOpen.Content = "开始服务";
}
}
}
}