Develop
2013.04.23 17:33

[c#] 간단한 소켓통신 예제..

Views 26692 Votes 0 Comment 0
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
// Server Socket
// NameSpace 선언
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ServerSideSocket
{
  class ServerClass
  {
    public static Socket Server , Client;
    
    public static byte[] getByte = new byte[1024];
    public static byte[] setByte = new byte[1024];
    
    public const int sPort = 5000;
    
    [STAThread]
    static void Main(string[] args)
    {
      string stringbyte = null;
      IPAddress serverIP = IPAddress.Parse("127.0.0.1");
      IPEndPoint serverEndPoint = new IPEndPoint(serverIP,sPort);
      
      try
      {      
        Server= new Socket(
          AddressFamily.InterNetwork,
          SocketType.Stream,ProtocolType.Tcp);
          
        Server.Bind(serverEndPoint);
        Server.Listen(10);

        Console.WriteLine("------------------------");
        Console.WriteLine("클라이언트의 연결을 기다립니다. ");
        Console.WriteLine("------------------------");
                  
        Client = Server.Accept();
  
        if(Client.Connected)
        {
          while(true)
          {
            Client.Receive(getByte,0,getByte.Length,SocketFlags.None);
            stringbyte = Encoding.UTF7.GetString(getByte);

            if (stringbyte != String.Empty)
            {
              int getValueLength = 0;
              getValueLength = byteArrayDefrag(getByte);
              
              stringbyte = Encoding.UTF7.GetString(
                getByte,0,getValueLength+1);

              Console.WriteLine("수신데이터:{0} | 길이:{1}",
                stringbyte,getValueLength+1);
                
              setByte = Encoding.UTF7.GetBytes(stringbyte);
              Client.Send(setByte,0,setByte.Length,SocketFlags.None);
            }
          
            getByte = new byte[1024];
            setByte = new byte[1024];
          }
        }
      }
        catch(System.Net.Sockets.SocketException socketEx)
      {
        Console.WriteLine("[Error]:{0}", socketEx.Message);
      }
      catch(System.Exception commonEx)
      {
        Console.WriteLine("[Error]:{0}", commonEx.Message);
      }
      finally
      {
        Server.Close();
        Client.Close();
      }
    }
    
    public static int byteArrayDefrag(byte[] sData)
    {
      int endLength = 0;
      
      for(int i = 0; i < sData.Length; i++)
      {
        if((byte)sData[i] != (byte)0)
        {
          endLength = i;
        }
      }
      
      return endLength; 
    }
  }
}


// Client Socket
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ClientSideSocket
{
  class ClientClass
  {
    public static Socket socket;
    public static byte[] getbyte = new byte[1024];
    public static byte[] setbyte = new byte[1024];

    public const int sPort = 5000;

    [STAThread]
    static void Main(string[] args)
    {
      string sendstring = null;
      string getstring = null;

      IPAddress serverIP = IPAddress.Parse("127.0.0.1");
      IPEndPoint serverEndPoint = new IPEndPoint(serverIP,sPort);

      socket = new Socket(
        AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        
      Console.WriteLine("------------------------------");
      Console.WriteLine(" 서버로 접속합니다.[엔터를 입력하세요] ");
      Console.WriteLine("------------------------------");
      Console.ReadLine();

      socket.Connect(serverEndPoint);

      if (socket.Connected)
      {
        Console.WriteLine(">>연결 되었습니다.(데이터를 입력하세요)");
      }

      while(true)
      {
        Console.Write(">>");
        sendstring = Console.ReadLine();
        
        if(sendstring != String.Empty)
        {
          int getValueLength = 0;
          setbyte = Encoding.UTF7.GetBytes(sendstring);
          
          socket.Send(setbyte,0,
            setbyte.Length,SocketFlags.None);
          
          Console.WriteLine("송신 데이터 : {0} | 길이{1}",
            sendstring, setbyte.Length);
            
          socket.Receive(getbyte,0,
            getbyte.Length,SocketFlags.None);
            
          getValueLength = byteArrayDefrag(getbyte);
          
          getstring = Encoding.UTF7.GetString(getbyte,
            0,getValueLength+1);
          
          Console.WriteLine(">>수신된 데이터 :{0} | 길이{1}",
            getstring , getValueLength+1);
        }
        
        getbyte = new byte[1024];
       }
    }
    
    public static int byteArrayDefrag(byte[] sData)
    {
      int endLength = 0;
      
      for(int i = 0; i < sData.Length; i++)
      {
        if((byte)sData[i] != (byte)0)
        {
          endLength = i;
        }
      }
      
      return endLength; 
    }
  }
}

?

List of Articles
No. Category Subject Author Date Views
725 System/OS [doc] 피쳐셀렉션(feature selection using..) 발표 자료 file hooni 2013.04.23 12546
724 System/OS [dos] 노트북 백업 스크립트 xcopy 명령 예제 hooni 2003.04.23 40805
723 Etc [english] 영어공부 혼자 하기, 인터넷으로 영어공부하기 추천사이트 20선 file hooni 2013.11.25 9408
722 Etc [eng] 숙제 ㅋㅋㅋ secret hooni 2015.10.14 1
721 Develop [erp] SAP 모듈 요약 hooni 2013.04.23 15283
720 Etc [flash] 맘에 드는 파이차트 file hooni 2013.04.23 12590
719 Etc [flash] 자동차 엔진의 원리 (4행정 사이클 그림) file hooni 2013.04.23 21224
718 Etc [flash] 페이지 이동 (액션스크립트) file hooni 2013.04.23 16263
717 Develop [git] 쉬운 버전관리 Git 설명 hooni 2015.08.18 872
716 Develop [html] HTML5 튜토리얼 링크 ㅋㅋ hooni 2013.04.23 12813
715 Develop [html] SVG(Scalable Vector Graphics) 간단 정리 hooni 2014.02.13 8831
714 Develop [html] 메타태그 사용예.. 은지나 바라~ hooni 2003.04.23 7227
713 Develop [html] 캐쉬된 웹페이지 사용하지 않도록 하는 방법 hooni 2003.04.23 13028
712 Etc [htm] DOM에 대해 ㅎㅎ file hooni 2003.04.23 14717
711 Develop [ios] UIView 계층구조 hooni 2015.01.03 1122
710 Develop [ios] @property의 속성 (strong, weak, copy) 사용 경우 hooni 2014.08.08 1656
Board Pagination Prev 1 ... 27 28 29 30 31 ... 74 Next
/ 74