//=============================================================== // Server : Start //=============================================================== public void ServerStartListen(string serverIP, int serverPort) { if (serverStatus == csConnStatus.Listening) { return; } if (serverStatus == csConnStatus.Connected) { return; } // Step 1 : Start try { // Getting IP object for server IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); // Getting server object listener = new TcpListener(serverAddress); // Start listener.Start(); } catch (SocketException e) { Console.WriteLine(e); return; } // Step 2 : start listening bool success = ServerBeginListen(); serverStatus = csConnStatus.Listening; }
//=============================================================== // Client Check Partner Death Thread //=============================================================== private void ClientCheckPartnerDeathThread() { try { while (true) { Thread.Sleep(5); // checks routinely if the connect is lost if (clientStatus == csConnStatus.Connected) { if (clientForClient != null && clientForClient.Client != null) { if (clientForClient.Client.Connected == false) { clientStatus = csConnStatus.Closed; } } } if (clientStatus != csConnStatus.Connected) { break; } } } catch { } }
//=============================================================== // Client : Try Connect [Async mode] //=============================================================== public void ClientBeginConnect(string serverIP, int serverPort, string clientIP) { if (clientStatus == csConnStatus.Connected) { return; } if (clientStatus == csConnStatus.Connecting) { return; } if (serverIP == "") { return; } // Get server IP object IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); // Get client IP object // port = 0 means getting random port int dumport = 0; IPEndPoint clientAddress = new IPEndPoint(IPAddress.Parse(clientIP), dumport); // Get client object clientForClient = new TcpClient(clientAddress); // Start trying to connect IPAddress serverIpAddress = IPAddress.Parse(serverIP); clientForClient.BeginConnect(serverIpAddress, serverPort, new AsyncCallback(DoConnectTcpClientCallback), clientForClient); clientStatus = csConnStatus.Connecting; }
//=============================================================== // Server Receive Thread Main //=============================================================== private void ServerReceiveThreadMain() { try { byte[] bytebuff = new byte[buffersize]; while (true) { Thread.Sleep(1); if (streamServer == null) { continue; } if (!streamServer.CanRead) { continue; } List <byte> ListByteBuff = new List <byte>(); byte[] byteTemp; //StringBuilder strbuff = new StringBuilder(); int nbyteRead = 0; // loop for when arrived data is larger than receive buffer size do { nbyteRead = streamServer.Read(bytebuff, 0, bytebuff.Length); // blocking if (nbyteRead == 0) { // Confirm partner close connection serverStatus = csConnStatus.Closed; ServerClose(); //<- has to call the method. } byteTemp = new byte[nbyteRead]; Array.Copy(bytebuff, 0, byteTemp, 0, nbyteRead); ListByteBuff.AddRange(byteTemp); //strbuff.AppendFormat("{0}", Encoding.UTF8.GetString(bytebuff, 0, nbyteRead)); }while (streamServer.DataAvailable); // Copy to recive buffer to the received data lock (serverRcvByteList) { serverRcvByteList.AddRange(ListByteBuff); } // Call Data receive callback if (DataArrivalCallback != null) { DataArrivalCallback(); } } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } }
//=============================================================== // Server Check Partner Death Thread //=============================================================== private void ServerCheckPartnerDeathThread() { try { while (true) { Thread.Sleep(5); // check continuously if connection is lost if (serverStatus == csConnStatus.Connected) { if (clientForServer != null && clientForServer.Client != null) { if (clientForServer.Client.Connected == false) { serverStatus = csConnStatus.Closed; } } } if (serverStatus != csConnStatus.Connected) { break; } } } catch { } }
//=============================================================== // Server : Start //=============================================================== public void ServerStartListen(string serverIP, int serverPort) { if (serverStatus == csConnStatus.Listening) { return; } if (serverStatus == csConnStatus.Connected) { return; } // 1단계 : Start try { // server측 접속 IP 객체 얻기 IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); // server 객체 얻기 listener = new TcpListener(serverAddress); // Start listener.Start(); } catch (SocketException e) { Console.WriteLine(e); return; } // 2단계 : Listen 시작 bool success = ServerBeginListen(); serverStatus = csConnStatus.Listening; }
//=============================================================== // Client Check Partner Death Thread //=============================================================== private void ClientCheckPartnerDeathThread() { try { while (true) { Thread.Sleep(5); // 상대방이 connected에서 갑자기 꺼져 버리면 // Closed로 바꾸는 방법이 정기적인 검사밖에 없음. // 상황보다 약간 늦게 알게되지만 상관없음. if (clientStatus == csConnStatus.Connected) { if (clientForClient != null && clientForClient.Client != null) { if (clientForClient.Client.Connected == false) { clientStatus = csConnStatus.Closed; } } } if (clientStatus != csConnStatus.Connected) { break; } } } catch { } }
private void tmrConnCheck_Tick(object sender, EventArgs e) { if (rB_tcp.Checked) { if (tServer == null) { lblStat.Text = "Conn: NULL"; } else { csConnStatus conn = tServer.ServerStatus(); lblStat.Text = "Conn: " + conn.ToString(); } } else if (rB_udp.Checked) { if (uServer == null) { lblStat.Text = "Conn: NULL"; } else { csUdpConnStatus conn = uServer.ServerStatus(); lblStat.Text = "Conn: " + conn.ToString(); } } }
//--------------------------------------------------------------- // Connect CallBack 함수 //--------------------------------------------------------------- private void DoConnectTcpClientCallback(IAsyncResult ar) { try { clientForClient = (TcpClient)ar.AsyncState; clientForClient.EndConnect(ar); streamClient = clientForClient.GetStream(); // stream 객체 얻기 // 수신 thread 시작 threadClientRcv = new Thread(ClientReceiveThreadMain); threadClientRcv.IsBackground = true; threadClientRcv.Start(); // 상대 돌발죽음 감시 thread 시작 threadChkPartnerDeath = new Thread(ClientCheckPartnerDeathThread); threadChkPartnerDeath.IsBackground = true; threadChkPartnerDeath.Start(); clientStatus = csConnStatus.Connected; } catch { clientStatus = csConnStatus.Closed; } }
//=============================================================== // Client : Connect 시도 [Async 모드] //=============================================================== public void ClientBeginConnect(string serverIP, int serverPort, string clientIP) { if (clientStatus == csConnStatus.Connected) { return; } if (clientStatus == csConnStatus.Connecting) { return; } if (serverIP == "") { return; } // server측 접속 IP 객체 얻기 IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); // client측 접속 IP 객체 얻기 // port = 0은 임의의 할당포트 사용하겠다는 뜻 int dumport = 0; IPEndPoint clientAddress = new IPEndPoint(IPAddress.Parse(clientIP), dumport); // client 객체 얻기 clientForClient = new TcpClient(clientAddress); // connected 시작 IPAddress serverIpAddress = IPAddress.Parse(serverIP); clientForClient.BeginConnect(serverIpAddress, serverPort, new AsyncCallback(DoConnectTcpClientCallback), clientForClient); clientStatus = csConnStatus.Connecting; }
//=============================================================== // Server : Close //=============================================================== public void ServerClose() { if (clientForServer != null) { clientForServer.Close(); } if (listener != null) { listener.Stop(); } while (true) { // listening중에 close되면 // DoAcceptTcpClientCallback()에서 listener처리할때까지 대기 if (listener == null) { break; } } // 순서 바뀌면 안됨 if (threadServerRcv != null && threadServerRcv.IsAlive) { threadServerRcv.Abort(); threadServerRcv.Join(); } if (threadChkPartnerDeath != null && threadChkPartnerDeath.IsAlive) { threadChkPartnerDeath.Abort(); threadChkPartnerDeath.Join(); } serverStatus = csConnStatus.Closed; }
//--------------------------------------------------------------- // Connect Callback method //--------------------------------------------------------------- private void DoConnectTcpClientCallback(IAsyncResult ar) { try { clientForClient = (TcpClient)ar.AsyncState; clientForClient.EndConnect(ar); streamClient = clientForClient.GetStream(); // Get stream object // Start receive thread threadClientRcv = new Thread(ClientReceiveThreadMain); threadClientRcv.IsBackground = true; threadClientRcv.Start(); // Start thread that checks partner connect death threadChkPartnerDeath = new Thread(ClientCheckPartnerDeathThread); threadChkPartnerDeath.IsBackground = true; threadChkPartnerDeath.Start(); clientStatus = csConnStatus.Connected; } catch { clientStatus = csConnStatus.Closed; } }
//=============================================================== // Client Receive Thread Main //=============================================================== private void ClientReceiveThreadMain() { try { byte[] bytebuff = new byte[buffersize]; while (true) { Thread.Sleep(1); if (streamClient == null) { continue; } if (!streamClient.CanRead) { continue; } byte[] byteTemp; List <byte> ListByteBuff = new List <byte>(); //StringBuilder strbuff = new StringBuilder(); int nbyteRead = 0; // Loop for when arrived data is larger than receive buffer size do { nbyteRead = streamClient.Read(bytebuff, 0, bytebuff.Length); // blocking if (nbyteRead == 0) { // Detect partner close the connection clientStatus = csConnStatus.Closed; ClientClose(); } byteTemp = new byte[nbyteRead]; Array.Copy(bytebuff, 0, byteTemp, 0, nbyteRead); ListByteBuff.AddRange(byteTemp); }while (streamClient.DataAvailable); // Copy to receive buffer lock (clientRcvByteList) { clientRcvByteList.AddRange(ListByteBuff); } // Call data receive callback method if (DataArrivalCallback != null) { DataArrivalCallback(); } } } catch { } }
private void tmChk_Tick(object sender, EventArgs e) { if (tcpServer == null) { lblStat.Text = "Status: NULL"; } else { csConnStatus conn = tcpServer.ServerStatus(); lblStat.Text = "Status: " + conn.ToString(); } }
//=============================================================== // Client Receive Thread Main //=============================================================== private void ClientReceiveThreadMain() { try { byte[] bytebuff = new byte[buffersize]; while (true) { Thread.Sleep(1); if (streamClient == null) { continue; } if (!streamClient.CanRead) { continue; } StringBuilder strbuff = new StringBuilder(); int nbyteRead = 0; // 도착 message가 buffer 크기보다 큰 경우를 위해 loop do { nbyteRead = streamClient.Read(bytebuff, 0, bytebuff.Length); // blocking if (nbyteRead == 0) { // 상대방이 close했음을 감지 clientStatus = csConnStatus.Closed; ClientClose(); } strbuff.AppendFormat("{0}", Encoding.UTF8.GetString(bytebuff, 0, nbyteRead)); }while (streamClient.DataAvailable); // 수신버퍼에 복사 lock (clientRcvMessage) //<- thread간 동기화 { clientRcvMessage += strbuff; } // 데이터 수신 callback 함수 호출 if (DataArrivalCallback != null) { DataArrivalCallback(); } } } catch { } }
//=============================================================== // Client : Close //=============================================================== public void ClientClose() { if (clientForClient != null) { clientForClient.Close(); } clientForClient = null; if (threadClientRcv != null && threadClientRcv.IsAlive) { threadClientRcv.Abort(); threadClientRcv.Join(); } if (threadChkPartnerDeath != null && threadChkPartnerDeath.IsAlive) { threadChkPartnerDeath.Abort(); threadChkPartnerDeath.Join(); } clientStatus = csConnStatus.Closed; }
//--------------------------------------------------------------- // Listen CallBack method //--------------------------------------------------------------- private void DoAcceptTcpClientCallback(IAsyncResult ar) { // exception process in case socket close happens while listening try { // Get the listener that handles the client request. listener = (TcpListener)ar.AsyncState; // End the operation clientForServer = listener.EndAcceptTcpClient(ar); // Get stream object streamServer = clientForServer.GetStream(); // Start receive thread threadServerRcv = new Thread(ServerReceiveThreadMain); threadServerRcv.IsBackground = true; threadServerRcv.Start(); // Start thread that checks unexpected connection death with partner threadChkPartnerDeath = new Thread(ServerCheckPartnerDeathThread); threadChkPartnerDeath.IsBackground = true; threadChkPartnerDeath.Start(); serverStatus = csConnStatus.Connected; } catch (Exception e) { Console.WriteLine(e); serverStatus = csConnStatus.Closed; } finally { // stop listener after connection established or cancelled listener.Stop(); listener = null; } }
//--------------------------------------------------------------- // Listen CallBack 함수 //--------------------------------------------------------------- private void DoAcceptTcpClientCallback(IAsyncResult ar) { try // Listen 대기중 Close 했을때의 exception 처리를 위해 { // Get the listener that handles the client request. listener = (TcpListener)ar.AsyncState; // End the operation clientForServer = listener.EndAcceptTcpClient(ar); // stream 객체 얻기 streamServer = clientForServer.GetStream(); // 수신 thread 시작 threadServerRcv = new Thread(ServerReceiveThreadMain); threadServerRcv.IsBackground = true; threadServerRcv.Start(); // 상대 돌발죽음 감시 thread 시작 threadChkPartnerDeath = new Thread(ServerCheckPartnerDeathThread); threadChkPartnerDeath.IsBackground = true; threadChkPartnerDeath.Start(); serverStatus = csConnStatus.Connected; } catch (Exception e) { Console.WriteLine(e); serverStatus = csConnStatus.Closed; } finally { // 연결되건, 최소되건 listener는 필요 없어짐 listener.Stop(); listener = null; } }
//=============================================================== // Server : Close //=============================================================== public void ServerClose() { if (clientForServer != null) { clientForServer.Close(); } if (listener != null) { listener.Stop(); } while (true) { // if server close happen when listening, // waiting until DoAcceptTcpClientCallback() finishes the listener object. if (listener == null) { break; } } // Close receive thread and connect death check thread // ** sequence of stopping threads has to be fixed. if (threadServerRcv != null && threadServerRcv.IsAlive) { threadServerRcv.Abort(); threadServerRcv.Join(); } if (threadChkPartnerDeath != null && threadChkPartnerDeath.IsAlive) { threadChkPartnerDeath.Abort(); threadChkPartnerDeath.Join(); } serverStatus = csConnStatus.Closed; }
//private void calculatePrimeNumber(int min, int max) //{ // // Recording Receiving Time // DateTime stime1 = DateTime.Now; // int cnt = 0; // IsPrime.Clear(); // NumPNOrg.Clear(); // for (int i = min; i <= max; i++) // { // if (isPrimeNumber(i)) // { // cnt++; // } // NumPNOrg.Add(cnt); // } // double dtime1 = Util.TimeInSeconds(stime1); //} //private bool isPrimeNumber(int n) //{ // int nchkmax = Convert.ToInt32(Math.Sqrt((double)n)); // bool isPrime = true; //Initialize Prime Flag // for (int i = 2; i <= nchkmax; i++) // { // if (n % i == 0) // { // isPrime = false; // break; // the number is not prime number // } // } // return isPrime; //} private void tmChk_Tick(object sender, EventArgs e) { if (clientCalc1 == null) { lblStat1.Text = "Status1: NULL"; lblRsp1.Text = "Respond1: NULL"; } else { csConnStatus conn = clientCalc1.ClientStatus(); lblStat1.Text = "Status1 : " + conn.ToString(); } if (clientCalc2 == null) { lblStat2.Text = "Status2: NULL"; lblRsp2.Text = "Respond2: NULL"; } else { csConnStatus conn = clientCalc2.ClientStatus(); lblStat2.Text = "Status2 : " + conn.ToString(); } }