Contents

Develop
2013.04.23 17:33

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

조회 수 26687 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
// 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
번호 분류 제목 글쓴이 날짜 조회 수
681 Develop [c#] 간단한 IPC 통신 예제 hooni 2013.04.23 63721
» Develop [c#] 간단한 소켓통신 예제.. hooni 2013.04.23 26687
679 Develop [c#] 비동기 통신 샘플 코드 ㅎㅎ file hooni 2013.04.23 23631
678 Develop [c#]업글 뉴 툴바 개인적으로 만든거.. (new) ㅋㅋ secret hooni 2013.04.23 7651
677 Develop [c#]뉴 툴바 개인적으로 만든거.. (new) secret hooni 2013.04.23 7724
676 Develop [c#]뉴 툴바 개인적으로 만든거.. (old) secret hooni 2013.04.23 4272
675 Develop 논문에 들어갈 툴바 테스트 해볼 것.. secret hooni 2013.04.23 8013
674 Develop 최근 논문 자료 (2011/01/03, 만현형한테 보낸거..) secret hooni 2013.04.23 10366
673 Develop [erp] SAP 모듈 요약 hooni 2013.04.23 15270
672 Develop [js] 양원님이 공유해 주신 유료(5$란다ㅋ) 자료 ㅋㅋ secret hooni 2013.04.23 7948
671 Develop [js] 동적(innerHTML)으로 자바스크립트 실행하기.. 2 file hooni 2013.04.23 18197
670 Develop [ios] Objective-C에서 SQLite 사용하기.. file hooni 2013.04.23 14554
Board Pagination Prev 1 ... 37 38 39 40 41 42 43 44 45 46 ... 98 Next
/ 98