using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public static Socket ClientSocket;
public static string IP = "192.168.0.200";
public static int port = 8899;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void SocketSendMessage(string CMD)
{
IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
ClientSocket.Connect(endPoint); //与远程主机建立连接
byte[] message = HexStrTobyte(CMD);
ClientSocket.Send(message);
byte[] receive = new byte[message.Length];
int length = ClientSocket.Receive(receive); // length 接收字节数组长度
richTextBox1.Text = DateTime.Now.ToString("HH:mm:ss") + ":" + byteToHexStr(receive)+"\n" + richTextBox1.Text;
ClientSocket.Close(); //关闭连接
}
private static byte[] HexStrTobyte(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).Trim(), 16);
return returnBytes;
}
// 字节数组转16进制字符串
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr = returnStr+" "+ bytes[i].ToString("X2");//ToString("X2") 为C#中的字符串格式控制符
}
}
return returnStr;
}
private void button1_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 00 00 01 48 0A");
}
private void button2_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 00 00 00 89 CA");
}
private void button4_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 01 00 01 19 CA");
}
private void button3_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 01 00 00 D8 0A");
}
private void button6_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 02 00 01 E9 CA");
}
private void button5_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 02 00 00 28 0A");
}
private void button8_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 03 00 01 B8 0A");
}
private void button7_Click(object sender, EventArgs e)
{
SocketSendMessage("01 06 00 03 00 00 79 CA");
}
private void button9_Click(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
}
private void button9_Click_1(object sender, EventArgs e)
{
richTextBox1.Text = "";
}
}
}