实例介绍
【实例简介】实现网口通讯
【实例截图】
【核心代码】
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);
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论