using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
namespace SocketClient
{
class Program
{
static Socket clientSocket;
static void Main(string[] args)
{
try
{
//将网络端点表示为IP地址和端口 用于socket侦听时绑定
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.216.99"), 19204);
clientSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
//将Socket连接到服务器
clientSocket.Connect(ipep);
//clientSocket.Bind(ipep);
String outBufferStr;
Byte[] outBuffer = new Byte[1024];
Byte[] inBuffer = new Byte[1024];
while (true)
{
//发送消息
outBufferStr = To16();
//outBuffer = Encoding.ASCII.GetBytes(outBufferStr);
outBuffer = strToToHexByte(outBufferStr);
clientSocket.Send(outBuffer, outBuffer.Length, SocketFlags.None);
Console.WriteLine("发送成功:" + To16());
//接收服务器端信息
clientSocket.Receive(inBuffer, 1024, SocketFlags.None);
Byte[] lenArr = new Byte[4];
Array.Copy(inBuffer, 4, lenArr, 0, 4);
if (BitConverter.IsLittleEndian)
Array.Reverse(lenArr);
uint len = System.BitConverter.ToUInt32(lenArr, 0);
Byte[] dataBuffer = new Byte[len];
Array.Copy(inBuffer, 16, dataBuffer, 0, len);
Console.WriteLine(Encoding.Default.GetString(dataBuffer));
string str=Encoding.Default.GetString(dataBuffer);
str = str.Substring(11, 4);
obstacles(str);
Console.WriteLine("信息:" + str);
Console.ReadKey();
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
Console.ReadLine();
}
}
public static string To16()
{
String HEAD = "5A01";
string BLOCKDATA = "000000000000";
string dataId = "0000";
string dataLength = "00000000";
//String dataType = "1006";
String data = "";
String datType2 = "03EE";
return HEAD + dataId + dataLength + datType2 + BLOCKDATA + data;
}
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
public static void obstacles(string flag)
{
if ("true".Equals(flag))
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "wscript.exe";
startInfo.Arguments = "C:\\Users\\user\\Desktop\\barrierRemind.vbs";
Process.Start(startInfo);
}
}
}
}