基本信息
源码名称:简单tcp 通讯网口工具客户端
源码大小:0.07M
文件格式:.zip
开发语言:C#
更新时间:2020-12-22
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
实现网口通讯
实现网口通讯
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Collections;
namespace 客户端33
{
public partial class Form1 : Form
{
private byte[] result = new byte[1024 * 1024];
private Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socket
public Socket newclient;//新建socket连接口
public bool Connected;
public Thread myThread;
public delegate void MyInvoke(string str);
public IPEndPoint myIe;
public IPAddress myIp;
public int myPort;
//send or receive
public byte[] myBy;//传递串口接收到的数据
public int myByLenth = 0;//串口接收到的数据长度
public string myStr;//串口接收的字符串
public bool receiveDtatFlag = false;
public bool myCloseForm = false;//防止窗口关闭时线程没有关闭占用资源
public bool myThreadStop = false;
public int send_count = 0;
public int recv_count = 0;
public Form1()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//;
string str = Console.ReadLine();
textBox1.Text = str;
}
private void button1_Click(object sender, EventArgs e)//发送数据按键
{
/*int m_length = rtbMySendMessage.Text.Length;
byte[] data = new byte[m_length];
data = Encoding.UTF8.GetBytes(rtbMySendMessage.Text);
int i = newclient.Send(data);*/
try
{
if (Connected)
{
//string s = "";
if (checkBox1.Checked)//十六进制发送
{
ArrayList al = cMyMathClass.Str16ToArrayList(textBox1.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
i ;
}
int mySendLenth = newclient.Send(by);
//serialPort1.Write(by, 0, i);//发送字节
//s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
}
else//ASCII发送
{
int m_length = textBox1.Text.Trim().Length;
byte[] data = new byte[m_length];
data = Encoding.UTF8.GetBytes(textBox1.Text);
int mySendLenth = newclient.Send(data);
//s = textBox1.Text;
//serialPort1.Write(s);//串口发送字符串
}
send_count ;
//MessageBox.Show(s);
}
else
{
MessageBox.Show("网络端口未打开!", "错误提示");
}
}
catch (Exception)
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
}
}
public void ReceiveMsg()//接收处理线程部分
{
while (myThreadStop)
{
string myRecvStrTemp = "";
#region 接收处理部分
if (myCloseForm == false)
{
try
{
byte[] data = new byte[1024];
int n = newclient.Receive(data);//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
if (n > 0)//有数据时才处理
{
StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。
long received_count = 0;//接收计数
byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
received_count = n;//增加接收计数
Array.Copy(data, 0, buf, 0, n);
//serialPort1.Read(buf, 0, n);//读取缓冲数据
builder.Clear();//清除字符串构造器的内容
myBy = buf;
myByLenth = buf.Length;
//因为要访问ui资源,所以需要使用invoke方式同步ui。
//this.Invoke((EventHandler)(delegate
//{
//判断是否是显示为16禁止
if (checkBox2.Checked)
{
//依次的拼接出16进制字符串
foreach (byte b in buf)
{
builder.Append(b.ToString("X2") " ");//在此实例的结尾追加指定字符串的副本
}
}
else
{
//直接按ASCII规则转换成字符串
builder.Append(Encoding.ASCII.GetString(buf));
}
//追加的形式添加到文本框末端,并滚动到最后。
myRecvStrTemp = builder.ToString();
//this.rtbReceiveMsg.AppendText(builder.ToString());
myStr = builder.ToString();//字符串输出
recv_count = n;//增加接收计数
}
}
catch (System.Exception ex)
{
Connected = false;
button2.Text = "连接服务器";
myThreadStop = false;
textBox2.Enabled = true;
textBox3.Enabled = true;
MessageBox.Show("与服务器断开 " ex.Message);
}
}
#endregion
showMsg(myRecvStrTemp);
}
}
public void showMsg(string msg)//接收显示处理部分
{
{
//在线程里以安全方式调用控件
if ((richTextBox2.InvokeRequired))
{
MyInvoke _myinvoke = new MyInvoke(showMsg);
richTextBox2.Invoke(_myinvoke, new object[] { msg });
}
else
{
richTextBox2.AppendText(msg);//显示部分
}
}
}//*/
#region 连接按钮处理
public void myConnect()//开启连接
{
//byte[] data = new byte[1024];
if (Connected == false)//没有连接
{
newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
myIp = IPAddress.Parse(textBox2.Text.Trim());
myPort = Convert.ToInt32(textBox3.Text.Trim());
myIe = new IPEndPoint(myIp, myPort);
try
{
newclient.Connect(myIe);
//btnConnect.Enabled = false;
Connected = true;
button2.Text = "断开连接";
myThreadStop = true;
textBox2.Enabled = false;
textBox3.Enabled = false;
}
catch (SocketException e)
{
Connected = false;
button2.Text = "连接服务器";
myThreadStop = false;
textBox2.Enabled = true;
textBox3.Enabled = true;
MessageBox.Show("连接服务器失败 " e.Message);
return;
}
//多线程处理
//ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
//myThread = new Thread(myThreaddelegate);
Thread myThread = new Thread(ReceiveMsg);//创建新线程
myThread.IsBackground = true;//线程后台运行
myThread.Start();//启动线程
}
else
{
Connected = false;
button2.Text = "连接服务器";
if (myThread != null)
{
myThread.Abort();
//Application.ExitThread();
}
myThreadStop = false;
newclient.Disconnect(false);
textBox2.Enabled = true;
textBox3.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)//连接服务器
{
myConnect();
}
#endregion 连接按钮处理
/* private void button3_Click(object sender, EventArgs e)
{
string s = textBox1.Text;
textBox1.Text= Encode(s);
}*/
public static string Encode(string strEncode)
{
string strReturn = "";// 存储转换后的编码
foreach (short shortx in strEncode.ToCharArray())
{
strReturn = shortx.ToString("X2");
}
return strReturn;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)//是否发送16进制
{
string s = "";
if (checkBox1.CheckState == CheckState.Checked)//发送HEX显示
{
byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(textBox1.Text);
textBox1.Text = "";
foreach (byte btmp in by)
{
s = "00" string.Format("{0:X}", btmp);
textBox1.Text = s.Substring(s.Length - 2, 2);
textBox1.Text = " ";
}
}
else//发送ASCII显示
{
ArrayList al = cMyMathClass.Str16ToArrayList(textBox1.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);
i ;
}
textBox1.Text = Encoding.GetEncoding("Gb2312").GetString(by);
}
}
}
}