기본 콘텐츠로 건너뛰기

C# - Multi Port Socket Programming (from MSDN Forum)

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;
                }
            }
        }
    }
}

댓글

이 블로그의 인기 게시물

C# - Serial Port ASCII/HEX Format

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();          ...

C# - Windows Form 에 있는 control 찾기

// 아래 코드는 form 의 최상위 control만 찾을 수 있음. // panle, groubbox ... 내부에 있는 control은 찾지 못함. Control GetControlByName(string Name) {     foreach (Control c in this.Controls)         if (c.Name == Name)             return c;     return null; } // form 의 모든 control을 찾을 수 있음. string name = "btnBit" + (i + 1).ToString("D2"); var tmpBtn = this.Controls.Find(name, true).FirstOrDefault(); if (tmpBtn != null) {     if (value == 1) tmpBtn.BackColor = Color.Lime;     else tmpBtn.BackColor = Color.Gray; }

C# - ARGB 색상

속성 A 이  Color  구조체의 알파 구성 요소 값을 가져옵니다. Alice Blue ARGB 값이  #FFF0F8FF 인 시스템 정의 색을 가져옵니다. Antique White ARGB 값이  #FFFAEBD7 인 시스템 정의 색을 가져옵니다. Aqua ARGB 값이  #FF00FFFF 인 시스템 정의 색을 가져옵니다. Aquamarine ARGB 값이  #FF7FFFD4 인 시스템 정의 색을 가져옵니다. Azure ARGB 값이  #FFF0FFFF 인 시스템 정의 색을 가져옵니다. B 이  Color  구조체의 파랑 구성 요소 값을 가져옵니다. Beige ARGB 값이  #FFF5F5DC 인 시스템 정의 색을 가져옵니다. Bisque ARGB 값이  #FFFFE4C4 인 시스템 정의 색을 가져옵니다. Black ARGB 값이  #FF000000 인 시스템 정의 색을 가져옵니다. Blanched Almond ARGB 값이  #FFFFEBCD 인 시스템 정의 색을 가져옵니다. Blue ARGB 값이  #FF0000FF 인 시스템 정의 색을 가져옵니다. Blue Violet ARGB 값이  #FF8A2BE2 인 시스템 정의 색을 가져옵니다. Brown ARGB 값이  #FFA52A2A 인 시스템 정의 색을 가져옵니다. Burly Wood ARGB 값이  #FFDEB887 인 시스템 정의 색을 가져옵니다. Cadet Blue ARGB 값이  #FF5F9EA0 인 시스템 정의 색을 가져옵니다. Chartreuse ARGB 값이  #FF7FFF00 인 시스템 정의 색을 가져옵니다. Chocolate ARGB 값이  #FFD2691E 인 시스템 정의 색을 가져옵니다. Coral ARGB ...