블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
반응형

Category

Recent Post

Recent Comment

Archive

'A Concern Interest/C#소켓프로그래밍'에 해당되는 글 3

  1. 2009.09.15 03장 C# Socket 활용
  2. 2009.09.15 02장 TCP Server&Client 활용
  3. 2009.09.15 01장.C# Socket 이란?
반응형

 Server Socket 작성하기
using System;
using System.Net.Sockets;
using System.Net
using System.Text;

public class SocketServer{

                                         public static void Main (string [] args)


IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);

Socket sListener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try {
       sListener.Bind(ipEndPoint);
       sListener.Listen(10); 
     
       while (true) {

                    Console.WriteLine("Waiting for a connection on port {0}",ipEndPoint); 
                    Clientsoket handler = sListener.Accept();
                    string data = null;
        while(true) {
                           byte[] bytes = new byte[1024];
                           int bytesRec = handler.Receive(bytes);
                           data += Encoding.ASCII.GetString(bytes,0,bytesRec);
                           if (data.IndexOf("") > -1)
                           {
                              break;
                           }
         }
Console.WriteLine("Text Received: {0}",data);
string theReply = "Thank you for those " + data.Length.ToString() + " characters...";
byte[] msg = Encoding.ASCII.GetBytes(theReply);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch(Exception e) {
                             Console.WriteLine(e.ToString());
}

}


 Client Socket 작성하기

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
public class SocketClient{
                        public static void Main (string [] args)
                        { 
                           byte[] bytes = new byte[1024];
                           try{
                                IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
                                IPAddress ipAddr = ipHost.AddressList[0];
                                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
                                Socket sender = new Socket
                            (AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

                                  sender.Connect(ipEndPoint); 
                                  Console.WriteLine("Socket connected to {0}",
                                                              sender.RemoteEndPoint.ToString());
                                                               string theMessage;

                                 if (args.Length==0)
                                         theMessage = "This is a test";
                                  else
                                         theMessage = args[0];
                                         byte[] msg = Encoding.ASCII.GetBytes(theMessage+"");
                                         int bytesSent = sender.Send(msg);
                                         int bytesRec = sender.Receive(bytes); 
                                         Console.WriteLine("The Server says : {0}",
                                          Encoding.ASCII.GetString(bytes,0, bytesRec));

                                          Sender.Shutdown(SocketShutdown.Both);
                                          sender.Close();
                                   } catch(Exception e)
                       {
                         Console.WriteLine("Exception: {0}", e.ToString()); 
                       }
             }

반응형

'A Concern Interest > C#소켓프로그래밍' 카테고리의 다른 글

02장 TCP Server&Client 활용  (0) 2009.09.15
01장.C# Socket 이란?  (0) 2009.09.15
posted by Magic_kit
반응형
 TCPClient.Cs
 소스(TcpClientExample.cs)

using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;

class TcpClientTest {
        static void Main(string[] args)
        {
                TcpClient client = null;
                try {
                     //LocalHost에 지정 포트로 TCP Connection을 생성하고 데이터를 송수신 하기
                     //위한 스트림을 얻는다.
                        client = new TcpClient();
                        client.Connect("localhost", 5001);
                        NetworkStream writeStream = client.GetStream();

                        //보낼 데이터를 읽어 Default 형식의 바이트 스트림으로 변환
                        string dataToSend = Console.ReadLine();        
                        byte [] data = Encoding.Default.GetBytes
                                            (dataToSend);                                                        
                        
                        while(true)
                        {                                                                
                                dataToSend += "\r\n";                                
                                data = Encoding.Default.GetBytes
                                           (dataToSend);                                
                                
                                writeStream.Write(data,0,data.Length);                                
                                
                                if (dataToSend.IndexOf("<EOF>") > -1) break;
                                        
                                dataToSend = Console.ReadLine();
                        }                                
                }
                catch(Exception ex) {
                        Console.WriteLine(ex.ToString());
                }
                finally {
                        client.Close();
                }
        }
}

 TCPServer.Cs
 using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;

class Server
{
   public static void Main()
   {  
          NetworkStream stream = null;
          TcpListener tcpListener = null;
          StreamReader reader = null;
          Socket clientsocket = null;
      try
      {              
                 //IP주소를 나타내는 객체를 생성,TcpListener를 생성시 인자로 사용할려고
                 IPAddress ipAd = IPAddress.Parse("127.0.0.1");

                 //TcpListener Class를 이용하여 클라이언트의 연결을 받아 들인다.
                 tcpListener = new TcpListener(ipAd, 5001);
                 tcpListener.Start();

        //Client의 접속이 올때 까지 Block 되는 부분, 대개 이부분을 Thread로 만들어 보내 버린다.
                 //백그라운드 Thread에 처리를 맡긴다.
                 clientsocket = tcpListener.AcceptSocket();

                 //클라이언트의 데이터를 읽고, 쓰기 위한 스트림을 만든다.
                 stream = new NetworkStream(clientsocket);
                                 
             Encoding encode = System.Text.Encoding.GetEncoding("ks_c_5601-1987");
             reader = new StreamReader(stream, encode);
            
                 while(true)
                 {                                
                         string str = reader.ReadLine();        
                         Console.WriteLine(str);                        
                 }                
      }
      catch (Exception e )
      {
         Console.WriteLine(e.ToString());
      }
          finally {
                clientsocket.Close();
          }
   }
}



반응형

'A Concern Interest > C#소켓프로그래밍' 카테고리의 다른 글

03장 C# Socket 활용  (0) 2009.09.15
01장.C# Socket 이란?  (0) 2009.09.15
posted by Magic_kit
반응형

1.  소켓이란 ?
    두 프로그램이 네트워크를 통해 서로 통신을 수행 할 수 있도록 양쪽에 생성되는 링크 단자이다.

2. 소켓형식
   스트림소켓 : 양방향으로 바이트 스트림을 전송 할 수있는 연결 지향형 소켓으로 양쪽
                    어플리케이션이 모두 데이터를 주고 받을 수 있다는 것을 의미
   데이터그램 소켓 : 명시적으로 연결을 맺지 않으므로 비 연결형 소켓이라고 한다
   Raw소켓 : 패킷을 가져오면 TCP/IP 스택상의 TCP, UDP 계층을 우회하여 바로
                 애플리케이션으로 송신하는 소켓

3. 포트
   여러 개의 애플리케이션들이 동시에 통신을 수행하기 위하여 포트가 정의 되는데 기본적으로
   포트는 IP 주소 표기를 확장 하는 개념 이다.
   네트워크에서 패킷을 수신하는 애플리케이션이 동시에 실행 되고 있는 컴퓨터로 연결을 맺을
   때 송신자가 알고 있는 수신 애플리케이션의 고유 포트 번호를 이용하여 대상 프로세스를 식별
   하는 것이다.

4. . Net 소켓 활용
-----------------------
 .NET 에서 소켓 다루기
-----------------------
System.Net.Sockets 네임스페이스의 클래스들은 .NET에서 지원하는 소켓들을 제공 한다.

System.Net.Sockets.MulticastOption :
                            IP 멀티캐스트 그룹에 참여 하거나 탈퇴하기 위한 IP 주소 값을 설정 한다.

System.Net.Sockets.NetworkStream : 데이터를 주고 받는 하위 스트림을 구현 한다. 
                                                   이는 TCP/IP 통신 채널에 대한 연결을 나타내는 고수준
                                                   추상형이다. 이 클래스를 이용하여 네크워크 소켓을 통해 
                                                   데이터를 주고 받을 수 있다. NetworkStream은 버퍼
                                                   기능이 지원되지 않으므로 BufferedStream을 중간 저장
                                                   매체로 함께 사용

System.Net.Sockets.TcpClient :
               Socket 클래스를 기반으로 하여 작성 되었으며 고수준 TCP 서비스를 제공하여 준다.

System.Net.Sockets.TcpListener :
                    Socket 클래스를 기반으로 작성 되었으며 서버 애플리케이션에서 사용 한다.
                    이 클래스는 들어오는 클라이언트의 연결을 리스닝 하며 애플리케이션에게 연결된
                    요청을 알려 준다.

System.Net.Sockets.UdpClient : UDP 서비스를 구현하기 위한 클래스

System.Net.Sockets.SocketException : 소켓에서 오류가 존재할 때 발생하는 예외

System.Net.Sockets.Socket : 소켓 애플리케이션의 기본 기능을 제공 한다.

------------------------
System.Net.Sockets.Socket
------------------------
Socket 클래스는 네트워크 프로그래밍에서 중요한 역할을 담당 하는데 클라이언트와 서버 사이의 모든 동작을 수행 한다.
윈도우 소켓 API의 해당 하는 메소드로 매핑 가능

소켓관련 속성)
AddressFamily : 소켓의 주소 계열을 획득, Socket.AddressFamily 열거형의 값 이다.
Available : 읽을 수 있는 데이터 량을 Return
Blocking : 소켓이 블로킹 모드 인지 확인
Connected : 소켓이 원격 호스트에 연결 되어 있는 지
LocalEndPoint : 로컬 종점을 돌려 줌
ProtocolType : 소켓의 프로토콜 형식을 돌려 준다.
SocketType : 소켓의 타입을 돌려 준다.

소켓 메서드)

Accept() : 들어오는 연결을 다루기 위한 새로운 소켓을 생성
Bind() : 들어오는 연결을 리스닝 하기 위하여 소켓을 로컬종점으로 연결
Close() : 소켓을 종료
Connect() : 원격 호스트에 연결을 맺는다.
Listen() : 리스닝 상태로 만든다, 이것은 서버 소켓에서만 사용 된다.
Receive() : 연결된 소켓으로부터 데이터를 수신 한다.
Send() : 연결된 소켓으로 데이터를 송신 한다.
Shutdown() : 소켓에 대한 연결을 비 활성화 한다.

반응형

'A Concern Interest > C#소켓프로그래밍' 카테고리의 다른 글

03장 C# Socket 활용  (0) 2009.09.15
02장 TCP Server&Client 활용  (0) 2009.09.15
posted by Magic_kit
prev 1 next