123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314 |
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Windows.Forms;
- namespace TestProject
- {
- class ModeBusTCPServer
- {
- private bool isOpen = false;
- Thread threadWatch = null; //负责监听客户端的线程
- Socket socketWatch = null; //负责监听客户端的套接字
- public bool IsOpen
- {
- get
- {
- return isOpen;
- }
- set
- {
- isOpen = value;
- }
- }
- public string IP
- {
- get
- {
- return iP;
- }
- set
- {
- iP = value;
- }
- }
- public string Port
- {
- get
- {
- return port;
- }
- set
- {
- port = value;
- }
- }
- private string iP;
- private string port;
- RichTextAutoBottom richtext;
- ComboBox SelectIP;
- ComboBox Encodingbox;
- Button SEND;
- RichTextAutoBottom SENDMESSAGE;
- public List<Socket> list = new List<Socket>();
- public ModeBusTCPServer()
- {
- }
- public bool Open()
- {
- try
- {
- Encodingbox = Application.OpenForms["MainWindow"].Controls["Encoding"] as ComboBox;
- SelectIP = Application.OpenForms["MainWindow"].Controls["SelectIP"] as ComboBox;
- richtext = Application.OpenForms["MainWindow"].Controls["Result"] as RichTextAutoBottom;
- SEND = Application.OpenForms["MainWindow"].Controls["SEND"] as Button;
- SENDMESSAGE = Application.OpenForms["MainWindow"].Controls["SENDMESSAGE"] as RichTextAutoBottom;
- SEND.Click += SEND_Click;
- //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
- socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //服务端发送信息 需要1个IP地址和端口号
- IPAddress ipaddress = IPAddress.Parse(iP);
- //将IP地址和端口号绑定到网络节点endpoint上
- IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port));
- //监听绑定的网络节点
- socketWatch.Bind(endpoint);
- //将套接字的监听队列长度限制为20
- socketWatch.Listen(20);
- //创建一个监听线程
- threadWatch = new Thread(WatchConnecting);
- //将窗体线程设置为与后台同步
- threadWatch.IsBackground = true;
- //启动线程
- threadWatch.Start();
- isOpen = true;
- return true;
- }
- catch (Exception e)
- {
- MessageBox.Show(e.Message);
- return false;
- }
- }
- private void SEND_Click(object sender, EventArgs e)
- {
- foreach (Socket item in list)
- {
- if (item != null)
- {
- if (item.RemoteEndPoint != null)
- {
- if (item.RemoteEndPoint.ToString() == SelectIP.Text)
- {
- switch (Encodingbox.Text)
- {
- case "UTF-8":
- item.Send(Encoding.UTF8.GetBytes(SENDMESSAGE.Text));
- break;
- case "ASCII":
- byte[] array = Encoding.ASCII.GetBytes(SENDMESSAGE.Text.Trim());
- string str = null;
- for (int i = 0; i < array.Length; i++)
- {
- int asciicode = (int)(array[i]);
- str += Convert.ToString(asciicode) + " ";
- }
- item.Send(Encoding.ASCII.GetBytes(str));
- break;
- case "Hexadecimal":
- char[] values = SENDMESSAGE.Text.ToCharArray();
- string strH = null;
- foreach (char letter in values)
- {
- // Get the integral value of the character.
- int value = Convert.ToInt32(letter);
- // Convert the decimal value to a hexadecimal value in string form.
- string hexOutput = string.Format("{0:X}", value);
- strH += hexOutput + " ";
- }
- item.Send(Encoding.UTF8.GetBytes(strH));
- break;
- }
- }
- }
- else
- {
- int index = SelectIP.Items.IndexOf(item.RemoteEndPoint.ToString());
- SelectIP.Items.RemoveAt(index);
- if (SelectIP.Items.Count > 0)
- {
- if (SelectIP.Text == "")
- SelectIP.Text = SelectIP.Items[0].ToString();
- }
- else
- SelectIP.Text = "";
- richtext.AppendText("客户端" + item.RemoteEndPoint + "已经中断连接" + "\r\n");
- if (list.Contains(item))
- {
- list.Remove(item);
- }
- //关闭之前accept出来的和客户端进行通信的套接字
- item.Close();
- }
- }
- }
- }
- private void WatchConnecting()
- {
- Socket connection = null;
- while (true) //持续不断监听客户端发来的请求
- {
- try
- {
- connection = socketWatch.Accept();
- }
- catch (SocketException e)
- {
- break;
- }
- //获取客户端的IP和端口号
- IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
- int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
- //让客户显示"连接成功的"的信息
- string sendmsg = "Connect Success!" + "LocalIP:" + clientIP + ",LocalPort" + clientPort.ToString();
- byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
- connection.Send(arrSendMsg);
- //客户端网络结点号
- string remoteEndPoint = connection.RemoteEndPoint.ToString();
- //显示与客户端连接情况
- richtext.AppendText("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
- SelectIP.Items.Add(clientIP + ":" + clientPort.ToString());
- SelectIP.SelectedItem = clientIP + ":" + clientPort.ToString();
- //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort);
- IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
- //创建一个通信线程
- ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
- Thread thread = new Thread(pts);
- //设置为后台线程,随着主线程退出而退出
- thread.IsBackground = true;
- //启动线程
- thread.Start(connection);
- //创建一个通信线程
- //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends);
- //Thread threadsed = new Thread(sed);
- //设置为后台线程,随着主线程退出而退出
- //threadsed.IsBackground = true;
- //启动线程
- //threadsed.Start(connection);
- list.Add(connection);
- }
- }
- void recv(object socketclientpara)
- {
- Socket socketServer = socketclientpara as Socket;
- while (true)
- {
- //创建一个内存缓冲区,其大小为1024*1024字节 即1M
- byte[] arrServerRecMsg = new byte[1024 * 1024];
- //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
- try
- {
- int length = socketServer.Receive(arrServerRecMsg);
- if (length == 0)
- {
- break;
- }
- //将机器接受到的字节数组转换为人可以读懂的字符串
- string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
- //将发送的字符串信息附加到文本框txtMsg上
- richtext.AppendText("客户端:" + socketServer.RemoteEndPoint + ",\r\n" + strSRecMsg + "\r\n\n");
- }
- catch (Exception)
- {
- if (socketServer.RemoteEndPoint != null)
- {
- //提示套接字监听异常
- int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
- SelectIP.Items.RemoveAt(index);
- if (SelectIP.Items.Count > 0)
- {
- if (SelectIP.Text == "")
- SelectIP.Text = SelectIP.Items[0].ToString();
- }
- else
- SelectIP.Text = "";
- richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
- }
- if (list.Contains(socketServer))
- {
- list.Remove(socketServer);
- }
- //关闭之前accept出来的和客户端进行通信的套接字
- socketServer.Close();
- break;
- }
- }
- if (socketServer != null)
- {
- if (socketServer.RemoteEndPoint != null)
- {
- int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
- SelectIP.Items.RemoveAt(index);
- if (SelectIP.Items.Count > 0)
- {
- if (SelectIP.Text == "")
- SelectIP.Text = SelectIP.Items[0].ToString();
- }
- else
- SelectIP.Text = "";
- richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
- }
- if (list.Contains(socketServer))
- {
- list.Remove(socketServer);
- }
- socketServer.Close();
- }
- }
- public void Close()
- {
- threadWatch.Abort();
- socketWatch.Close();
- isOpen = false;
- }
- public void SendOrder(string Code)
- {
- switch (Code)
- {
- default:
- break;
- }
- }
- }
- }
|