找传奇、传世资源到传世资源站!

TCP通信

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

from clipboardusing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading.Tasks;using System.Data.SqlClient;using System.IO;using System.Xml;using System.Text.RegularExpressions;using System.Runtime.InteropServices;using System.Net;using System.Net.Sockets;using System.Threading;using System.Diagnostics;namespace TCPdemo{ public partial class Form1 : Form { SocketTCP _SocketTCP = new SocketTCP(); public Form1() { InitializeComponent(); _SocketTCP.InitSocket("232", 1000); } private void Form1_Load(object sender, EventArgs e) { SendRequire(); } private void btnAdd_Click(object sender, EventArgs e) { SendRequireAdd(); } #region 发送目标数 目标数 1 public void SendRequire() { MessageInfovalue.head = "A0"; //string strInfo = (Convert.ToDouble((txtNum.Text).ToString()) - // Convert.ToDouble((txt_pckedNum.Text).ToString())).ToString(); string strInfo = "100"; MessageInfovalue.info = strInfo; byte[] text = new byte[256]; StructureToByte(MessageInfovalue, text); _SocketTCP.SendCommand(text); } public void SendRequireAdd() { MessageInfovalue.head = "C0"; string strInfo = "1"; MessageInfovalue.info = strInfo; byte[] text = new byte[256]; StructureToByte(MessageInfovalue, text); _SocketTCP.SendCommand(text); } #endregion #region TCP public MessageInfo MessageInfovalue = new MessageInfo(); //结构体转byte数组 public static void StructureToByte(object structObj, byte[] targetData) { IntPtr tmptr = IntPtr.Zero; try { int size = Marshal.SizeOf(structObj); // 获取结构体在内存中的大小 tmptr = Marshal.AllocHGlobal(size); // 为缓冲区分配内存空间 Marshal.StructureToPtr(structObj, tmptr, false); //Copy到分配的非托管内存中 Marshal.Copy(tmptr, targetData, 0, size); Marshal.FreeHGlobal(tmptr); } catch (Exception ex) { if (tmptr != IntPtr.Zero) Marshal.FreeHGlobal(tmptr); throw new Exception("内存操作失败:" ex.ToString()); } } /// <summary> /// byte数组转结构体 /// </summary> /// <param name="bytes">byte数组</param> /// <param name="type">结构体类型</param> /// <returns>转换后的结构体</returns> public static object BytesToStuct(byte[] bytes, MessageInfo type) { //得到结构体的大小 int size = Marshal.SizeOf(type); //byte数组长度小于结构体的大小 if (size > bytes.Length) { //返回空 return null; } //分配结构体大小的内存空间 IntPtr structPtr = Marshal.AllocHGlobal(size); //将byte数组拷到分配好的内存空间 Marshal.Copy(bytes, 0, structPtr, size); //将内存空间转换为目标结构体 object obj = Marshal.PtrToStructure(structPtr, typeof(MessageInfo)); //释放内存空间 Marshal.FreeHGlobal(structPtr); //返回结构体 return obj; } [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct MessageInfo { //字符串,SizeConst为字符串的最大长度 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)] public string head; //字符串,SizeConst为字符串的最大长度 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)] public string info; } public class SocketTCP { static readonly object padlock = new object(); byte[] data = new byte[1024]; IPAddress _IP; static IPEndPoint _ipEnd; static Socket socket; private static Object thisLock = new Object(); public SocketTCP() { } public SocketTCP(string IP, int Port) { InitSocket(IP, Port); } public bool InitSocket(string IP, int Port) { try { // _IP = IPAddress.Parse("100.168.0.6"); _IP = IPAddress.Parse("127.0.0.1"); _ipEnd = new IPEndPoint(_IP, 8000); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (ConnectServer()) { Thread reset_thread = new Thread(reset_connect); //重新连接线程 reset_thread.Start(); Thread socket_thread = new Thread(recv_thread); socket_thread.Start(); return true; } else return false; } catch { return false; } } public bool Connected { get { if (socket == null) return false; return socket.Connected; } } public bool ConnectServer() { try { socket.Connect(_ipEnd); recv_flag = true; return true; } catch (Exception) { return false; } } public bool Close() { try { // if (socket.Connected) socket.Shutdown(SocketShutdown.Both); socket.Close(); return true; } catch { return false; } } public int StatusCode { get; set; } public static bool recv_flag = false; public static bool error_thread_flat = false; public static void reset_connect() { while (true) { try { if (error_thread_flat) //此处可以用信号量处理让线程休眠,降低CPU { if (!socket.Connected) { socket.Close(); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(_ipEnd); } error_thread_flat = true; } } catch (Exception EX) { MessageBox.Show(EX.Message); Thread.Sleep(5000); continue; } } } public static void recv_thread() { MessageInfo obj = new MessageInfo(); MessageInfo obj1 = new MessageInfo(); byte[] data = new byte[256]; while (true) { if (recv_flag) { try { if (socket.Connected) { error_thread_flat = false; int count = socket.Receive(data); BytesToStuct(data, obj); object info = BytesToStuct(data, obj); obj1 = (MessageInfo)info; string head = obj1.head.ToString(); string strInfo = obj1.info.ToString(); switch (head) { case "B1": MessageBox.Show("打标已到目标数."); break; case "A1": if (strInfo == "1") { MessageBox.Show("发送目标打码数成功."); } break; case "C1": if (strInfo == "1") { MessageBox.Show("目标数加一成功."); } break; } } else { error_thread_flat = true; } } catch (Exception ex) { error_thread_flat = true; MessageBox.Show(ex.Message); } } } } public void SendCommand(byte[] cmd) { byte[] value = null; lock (thisLock) { if (socket != null) { if (socket.Connected) { socket.Send(cmd); } } } } } } #endregion}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复