关于网络通讯助手的编写(用socket实现)
1、声明 两个socket对象:
Socket aimSocket;//用来接收的Socket对象
Socket mySocket;//用来发送的Socket对象
2、获取本机IP地址:
string AddressIP = "";
foreach (IPAddress Address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (Address.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = Address.ToString();
_ip = Address;//设定全局的IP
}
}
return AddressIP;
3、对socket的配置:
//使用指定的地址族、套接字类型和协议初始化Socket 类的实例
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4、端口号的设置及绑定:
point = new IPEndPoint(_ip, Convert.ToInt32(txbPort.Text));//绑定端口号
mySocket.Bind(point);//绑定监听端口
private void TSReceive()
{
aimSocket = mySocket.Accept();//服务端监听到的Socket为服务端发送数据的目标socket
byte[] buffer = new byte[1024];
while (true)
{
try
{
//接收到监听的Socket的数据字节数
int r = aimSocket.Receive(buffer);
if (r == 0)
{
MessageBox.Show("连接断开");
break;
}
//在bufeer数组里面,从第0个字节开始解码,读取r个字节数
string strRec = Encoding.Default.GetString(buffer, 0, r);
txbNexReceiveMessage.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec "\r\n");
}
catch
{
}
}
}
6、数据发送:
byte[] buffer = Encoding.Default.GetBytes(txbNetSendMessage.Text);
aimSocket.SendTo(buffer, point);
7、完整代码。增加了串口通讯
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.IO;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Communication
public partial class Form1 : Form
{
SerialPort comm = new SerialPort();
StringBuilder builder = new StringBuilder();
IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
Socket aimSocket;
Socket mySocket;
IPAddress _ip;
string commStye = "";
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//关闭跨线程检测
txbIP.Text = GetAddress();
iniPort();
}
#region Serial Port Communication
private void Form1_Load(object sender, EventArgs e)
{
comm.DataReceived += comm_DataReceived;
}
private void OpenSerialPort_Click(object sender, EventArgs e)
{
try
{
btn_seriralportopen.Enabled = false;
btn_ColoseSerialPort.Enabled = true;
comm.Open();
}
catch
{
MessageBox.Show("串口打开异常");
}
}
private void CloseSerialPort_Click(object sender, EventArgs e)
{
comm.Close();
btn_seriralportopen.Enabled = true;
btn_ColoseSerialPort.Enabled = false;
}
private void iniPort()
{
try
{
string[] port = SerialPort.GetPortNames();
//comm.PortName = "COM11";
comm.PortName = port[0];
cmbPort.Text = port[0];
cmbPort.Items.AddRange(port);
cmbBaudRate.SelectedIndex = cmbBaudRate.Items.IndexOf(comm.BaudRate.ToString());
cmb_DataSbit.SelectedIndex = 0;
cmbParityBit.SelectedIndex = 0;
cmbStopBit.SelectedIndex = 0;
rdbASCII.Checked = true;
switch(cmbParityBit.Text)
{
case "NONE": comm.Parity = Parity.None; break;
case "ODD": comm.Parity = Parity.Odd;break;
case "EVEN": comm.Parity = Parity.Even; break;
default: comm.Parity = Parity.None; break;
}
}
catch
{
MessageBox.Show("串口初始化异常!");
}
}
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (rdbASCII.Checked)
{
int bytecount = comm.BytesToRead;
byte[] buf = new byte[bytecount];
comm.Read(buf, 0, bytecount);
string gb = System.Text.Encoding.Default.GetString(buf);
UpdateReceiveMessage(gb, true);
}
else if(rdbHex.Checked)
{
string str = Convert.ToString((byte)comm.ReadByte(),16).ToUpper();
UpdateReceiveMessage("0x" + (str.Length == 1 ? "0" + str : str) + "", true);
}
}
private void reflashPort()
{
if (cmbPort.SelectedIndex <0)
cmbPort.Items.AddRange(SerialPort.GetPortNames());
}
private void btn_reflashClick(object sender, EventArgs e)
{
reflashPort();
cmbPort.SelectedIndex = cmbPort.Items.Count > 0 ? 0 : -1;
}
private void UpdateReceiveMessage(string text,bool isReceived)
{
txb_ReceiveMessage.AppendText(string.Format("{0} - {1}:\r\n{2}\r\n",DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
isReceived ? "收到" : "发送", text));
}
private void bt_sendMassege_Click(object sender, EventArgs e)
{
if (comm.IsOpen)
{
if (txb_SendMessage != null)
{
if (rdbASCII.Checked)
{
try
{
Encoding gb = System.Text.Encoding.GetEncoding("gb2312");
byte[] bytes = gb.GetBytes(txb_SendMessage.Text);
comm.Write(bytes, 0, bytes.Length);
}
catch
{
MessageBox.Show("发送数据产生错误!");
comm.Close();
}
}
}
}
}
private void btn_ClearReceiveMesage_Click(object sender, EventArgs e)
{
txb_ReceiveMessage.Clear();
}
private void btn_ClearSendMessage_Click(object sender, EventArgs e)
{
txb_SendMessage.Clear();
}
#endregion
private string GetAddress()
{
string AddressIP = "";
foreach (IPAddress Address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (Address.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = Address.ToString();
_ip = Address;//设定全局的IP
}
}
return AddressIP;
}
private void cmbNetType_SelectedIndexChanged(object sender, EventArgs e)
{
commStye = cmbNetType.SelectedItem.ToString();
}
private void btConnect_Click(object sender, EventArgs e)
{
try
{
if (commStye == "TCP Server")
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
point = new IPEndPoint(_ip, Convert.ToInt32(txbPort.Text));//绑定端口号
mySocket.Bind(point);//绑定监听端口
MessageBox.Show("TCP Server绑定成功");
mySocket.Listen(10);//等待连接是一个阻塞过程,创建线程来监听
Thread thReceive = new Thread(TSReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
else if (commStye == "TCP Client")
{
_ip = IPAddress.Parse(txbIP.Text);//目标IP
point = new IPEndPoint(_ip, Convert.ToInt32(txbPort.Text));//目标端口
aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
aimSocket.Connect(point);//连接服务器
MessageBox.Show("连接成功");
Thread thReceive = new Thread(TCReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
}
catch
{
MessageBox.Show("网络端口打开异常");
}
}
private void TSReceive()
{
aimSocket = mySocket.Accept();//服务端监听到的Socket为服务端发送数据的目标socket
byte[] buffer = new byte[1024];
while (true)
{
try
{
//接收到监听的Socket的数据字节数
int r = aimSocket.Receive(buffer);
if (r == 0)
{
MessageBox.Show("连接断开");
break;
}
//在bufeer数组里面,从第0个字节开始解码,读取r个字节数
string strRec = Encoding.Default.GetString(buffer, 0, r);
//192.168.1.61:800:你好
txbNexReceiveMessage.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec + "\r\n");
}
catch
{
}
}
}
private void TCReceive()
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
int r = aimSocket.Receive(buffer);
if (r == 0)
{
MessageBox.Show("连接断开");
break;
}
string strRec = Encoding.Default.GetString(buffer, 0, r);
//192.168.1.61:47380:你好啊
txbNexReceiveMessage.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec + "\r\n");
}
catch
{
}
}
}
private void btSend_Click(object sender, EventArgs e)
{
try
{
byte[] buffer = Encoding.Default.GetBytes(txbNetSendMessage.Text);
aimSocket.SendTo(buffer, point);
}
catch
{
MessageBox.Show("数据发送异常!");
}
}
private void btReceive_Click(object sender, EventArgs e)
{
txbNexReceiveMessage.Clear();
}
private void btClearSend_Click(object sender, EventArgs e)
{
txbNetSendMessage.Clear();
}
}
}