使用方法在 無線感測網路協定與應用(1)
以下是包含讀取COM阜並架設Server後,傳值到Client端的程式碼。
using 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.IO.Ports;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class DataTransmit : Form
{
Boolean connection = false;
private SerialPort comport;
private Socket sock;
private List sockc = new List();
private string LocalIP;
public DataTransmit()
{
InitializeComponent();
}
public string comRecv = "";
private string ServerInfo = "";
private bool SockState = false;
private void button1_Click(object sender, EventArgs e)
{
if (connection == false)
{
connection = true;
comport = CreateComport(comport);
label3.Text = "連線成功";
this.button1.Text = "斷線";
OpenComport(comport);
}
else if (connection == true)
{
connection = false;
CloseComport(comport);
label3.Text = "尚未連線";
this.button1.Text = "連線";
}
}
private void OpenComport(SerialPort port)
{
try
{
if ((port != null) && (!port.IsOpen))
{
port.Open();
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("出問題啦:{0}", ex.ToString()));
connection = false;
}
}
private void CloseComport(SerialPort port)
{
try
{
port.Close();
MessageBox.Show("序列埠已關閉");
}
catch (Exception ex)
{
connection = true;
MessageBox.Show(String.Format("序列埠出問題啦:{0}", ex.ToString()));
}
}
private SerialPort CreateComport(SerialPort port)
{
try
{
port = new SerialPort(textBox1.Text, 9600, Parity.None, 8, StopBits.One);
}
catch (System.IO.IOException e)
{
port = null;
}
return port;
}
private void timer1_Tick(object sender, EventArgs e)
{
this.label8.Text = comRecv;
this.textBox2.Text = ServerInfo;
//* sock send to ALL Client
try
{
//int count = sockc.Count;
for (int i = 0; i < sockc.Count; i++)
if (sockc != null)
if (sockc[i].Connected)
sockc[i].Send(Encoding.UTF8.GetBytes(this.label8.Text + "\n"));
}
catch { }
//* Read Com Data
if (connection)
{
string Strtmp = comRecv;
if (comport.BytesToRead > 0)
{
byte[] tmp = new byte[4096];
comport.Read(tmp, 0, 4096);
comRecv = Encoding.ASCII.GetString(tmp).Trim();
}
string[] ttmp = comRecv.Split('\n');
if (ttmp.Length > 1)
comRecv = ttmp[ttmp.Length - 2];
else if (ttmp.Length > 0)
comRecv = ttmp[ttmp.Length - 1];
else
comRecv = Strtmp;
if (comRecv == "")
comRecv = Strtmp;
comRecv = comRecv.Trim();
}
}
//*Server Open
private void button2_Click(object sender, EventArgs e)
{
// 取得本機名稱
string strHostName = Dns.GetHostName();
// 取得本機的IpHostEntry類別實體
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
// 取得所有 IP 位址
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
// 只取得IP V4的Address
if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
LocalIP = ipaddress.ToString();
}
}
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(new IPEndPoint(IPAddress.Parse(LocalIP), Convert.ToInt32(PORT.Text)));
ServerInfo = "[Server]:Server is open [IP = " + LocalIP + "][PORT = " + PORT.Text + "]";
this.Text = "[Server]:[IP = " + LocalIP + "][PORT = " + PORT.Text + "]";
sock.Listen(10); // 進行聆聽; Listen( )為允許 Client 同時連線的最大數
SockState = true;
this.button2.Enabled = false;
new Thread(new ThreadStart(Accept)).Start();
}
private void Accept()
{
//* Accept Client
while (SockState)
{
try
{
Socket n;
n = sock.Accept(); // 等待Client 端連線
ServerInfo = n.RemoteEndPoint.ToString() + " ISCONNECTED";
sockc.Add(n);
}
catch (Exception ex)
{
MessageBox.Show("Server is close.");
}
}
}
//* FormClose -> close sock Server
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(sock!=null)
this.sock.Close();
this.SockState = false;
}
}
}
發行檔:載點
沒有留言:
張貼留言