using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.Win32; using System.Runtime.InteropServices; namespace ServerOnCE { public partial class MainForm : Form { private TcpListener listener; private RegistryKey reg = Registry.LocalMachine; private Socket socket; [DllImport("DataAcquisition.dll")] public static extern void FPGA_init(); [DllImport("DataAcquisition.dll")] public static extern void FPGA_release(); [DllImport("DataAcquisition.dll")] public static extern void LedControl(Int32 iLedNumber, Boolean bState); public static bool b0 = true; public MainForm() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (this.txtPort.Text == "" || this.txtPort.Text == null) { MessageBox.Show("请输入端口"); } else { int port = Convert.ToInt32(this.txtPort.Text); listener = new TcpListener(port); listener.Start(); Thread thread = new Thread(new ThreadStart(target)); thread.Start(); MessageBox.Show("服务器已经开启,按确定关闭服务"); thread.Abort(); listener.Stop(); socket.Close(); } } /// <summary> /// 接受控制信息. /// </summary> public void target() { socket = listener.AcceptSocket(); while (socket.Connected) { byte[] by = new Byte[6]; int i = socket.Receive(by, by.Length, 0); string ss = System.Text.Encoding.ASCII.GetString(by,0,by.Length); //接收连接测试指令,反馈信息提示连接成功. if (ss == "Tesing") { string str = "con"; byte[] newbyte = System.Text.Encoding.ASCII.GetBytes(str.ToCharArray()); socket.Send(newbyte, newbyte.Length, 0); //socket.Shutdown(SocketShutdown.Both); } //接收到不同的指令所进行的操作. //控制码为cmdLED,控制LED if (ss == "cmdLED") { try { string str = "led"; byte[] newbyte = System.Text.Encoding.ASCII.GetBytes(str.ToCharArray()); socket.Send(newbyte, newbyte.Length, 0); try { //FPGA_init(); if (b0) { LedControl(0, true); LedControl(1, false); b0 = false; } else { LedControl(0, false); LedControl(1, true); b0 = true; } //FPGA_release(); } catch { MessageBox.Show("LED命令调用失败"); } } catch { MessageBox.Show("Socket异常"); } //socket.Shutdown(SocketShutdown.Both); //socket.Close(); } } } } }