using System; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Collections.Generic; namespace DefaultNamespace { public partial class SocketServer : Form { private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.RichTextBox richTextBoxReceivedMsg; private System.Windows.Forms.TextBox textBoxPort; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBoxMsg; private System.Windows.Forms.Button buttonStopListen; private System.Windows.Forms.Label label1; private System.Windows.Forms.RichTextBox richTextBoxSendMsg; private System.Windows.Forms.TextBox textBoxIP; private System.Windows.Forms.Button buttonStartListen; private System.Windows.Forms.Button buttonSendMsg; private System.Windows.Forms.Button buttonClose; Server server; static SocketServer ThisForm; public SocketServer() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); ThisForm = this; server = new Server(this); // Display the local IP address on the GUI textBoxIP.Text = GetIP(); } public String GetIP() { String strHostName = Dns.GetHostName(); // Find host by name IPHostEntry iphostentry = Dns.GetHostEntry(strHostName); IPAddress LocalHostIP = iphostentry.AddressList[0]; return LocalHostIP.ToString(); } void ButtonStartListenClick(object sender, System.EventArgs e) { try { // Check the port value if (textBoxPort.Text == "") { MessageBox.Show("Please enter a Port Number"); return; } server.StartListeners(textBoxPort.Text); UpdateControls(true); } catch (SocketException se) { MessageBox.Show(se.Message); } } public void DisplayTextBoxMsg(string message) { if (textBoxMsg.InvokeRequired) textBoxMsg.Invoke(new MethodInvoker(delegate { textBoxMsg.Text = message; })); else textBoxMsg.Text = message; } public void DisplayRichTextBoxReceivedMsg(string message) { if (richTextBoxReceivedMsg.InvokeRequired) richTextBoxReceivedMsg.Invoke(new MethodInvoker(delegate { richTextBoxReceivedMsg.AppendText(message); })); else richTextBoxReceivedMsg.Text = message; } public string GetRichTextBoxSendMsg() { string results = ""; if (richTextBoxSendMsg.InvokeRequired) richTextBoxSendMsg.Invoke(new MethodInvoker(delegate { results = richTextBoxSendMsg.Text; })); else results = richTextBoxSendMsg.Text; return results; } private void UpdateControls(bool listening) { buttonStartListen.Enabled = !listening; buttonStopListen.Enabled = listening; } void ButtonSendMsgClick(object sender, System.EventArgs e) { try { server.SendMsgClick(richTextBoxSendMsg.Text); } catch (SocketException se) { MessageBox.Show(se.Message); } } void ButtonStopListenClick(object sender, System.EventArgs e) { server.CloseSockets(); UpdateControls(false); } void ButtonCloseClick(object sender, System.EventArgs e) { server.CloseSockets(); Close(); } } class Server { SocketServer socketServerForm; const int MAX_CLIENTS = 10; public AsyncCallback pfnWorkerCallBack; private List<Socket> m_mainSockets = new List<Socket>(); private List<Socket> m_workerSocket = new List<Socket>(); public Server(SocketServer form) { socketServerForm = form; } class State { public int index = 0; public int port; } class ReceiveDataState { public SocketPacket socketData; public int port; } public void StartListeners(string ports) { string[] portStrs = ports.Split(','); int index = 0; foreach (string portStr in portStrs) { int port = System.Convert.ToInt32(portStr); State state = new State(); state.index = index++; state.port = port; // Create the listening socket... Socket new_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port); // Bind to local IP Address... new_mainSocket.Bind(ipLocal); // Start listening... new_mainSocket.Listen(4); // Create the call back for any client connections... new_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), state); m_mainSockets.Add(new_mainSocket); } } // This is the call back function, which will be invoked when a client is connected public void OnClientConnect(IAsyncResult asyn) { var state = asyn.AsyncState as State; var port = state.port; var m_mainSocket = m_mainSockets[state.index]; try { // Here we complete/end the BeginAccept() asynchronous call // by calling EndAccept() - which returns the reference to // a new Socket object //var m_mainSocket = m_mainSocket.EndAccept(asyn); m_workerSocket.Add(m_mainSocket.EndAccept(asyn)); // Let the worker Socket do the further processing for the // just connected client WaitForData(m_workerSocket[m_workerSocket.Count - 1], port); // Now increment the client count // Display this client connection as a status message on the GUI String str = String.Format("Client # {0} connected", m_workerSocket.Count - 1); socketServerForm.DisplayTextBoxMsg(str); // Since the main Socket is now free, it can go back and wait for // other clients who are attempting to connect m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), state); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } } public class SocketPacket { public System.Net.Sockets.Socket m_currentSocket; public byte[] dataBuffer = new byte[1]; } // Start waiting for data from the client public void WaitForData(System.Net.Sockets.Socket soc, int port) { try { if (pfnWorkerCallBack == null) { // Specify the call back function which is to be // invoked when there is any write activity by the // connected client pfnWorkerCallBack = new AsyncCallback(OnDataReceived); } ReceiveDataState state = new ReceiveDataState(); SocketPacket theSocPkt = new SocketPacket(); state.socketData = theSocPkt; state.port = port; theSocPkt.m_currentSocket = soc; // Start receiving any data written by the connected client // asynchronously soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, state); } catch (SocketException se) { MessageBox.Show(se.Message); } } // This the call back function which will be invoked when the socket // detects any client writing of data on the stream public void OnDataReceived(IAsyncResult asyn) { try { var state = asyn.AsyncState as ReceiveDataState; var socketData = state.socketData; var port = state.port; int iRx = 0; // Complete the BeginReceive() asynchronous call by EndReceive() method // which will return the number of characters written to the stream // by the client iRx = socketData.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); socketServerForm.DisplayRichTextBoxReceivedMsg(szData); // Continue the waiting for data on the Socket WaitForData(socketData.m_currentSocket, state.port); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } } public void SendMsgClick(string message) { try { Object objData = message; byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString()); for (int i = 0; i < m_workerSocket.Count; i++) { if (m_workerSocket[i] != null) { if (m_workerSocket[i].Connected) { m_workerSocket[i].Send(byData); } } } } catch (SocketException se) { MessageBox.Show(se.Message); } } public void CloseSockets() { foreach (Socket m_mainSocket in m_mainSockets) { if (m_mainSocket != null) { m_mainSocket.Close(); } } for (int i = 0; i < m_workerSocket.Count; i++) { if (m_workerSocket[i] != null) { m_workerSocket[i].Close(); m_workerSocket[i] = null; } } } } }
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; namespace SerialTest1 { public partial class Form1 : Form { delegate void MyDelegate(); //델리게이트 선언(크로스 쓰레드 해결하기 위한 용도) bool SendForamt = true; // true : ASCII false : HEX bool ReceiveFormat = true; // true : ASCII false : HEX public Form1() { InitializeComponent(); ...
댓글