public byte[] encode(ItemQuote item)
        {
            String EncodedString = item.itemNumber + " ";

            if (item.itemDescription.IndexOf('\n') != -1)
            {
                throw new IOException("Invalid description (contains newline)");
            }
            EncodedString = EncodedString + item.itemDescription + "\n";
            EncodedString = EncodedString + item.quantity + " ";
            EncodedString = EncodedString + item.unitPrice + " ";

            if (item.discounted)
            {
                EncodedString = EncodedString + "d";        // 할인 적용 시 'd' 추가
            }
            if (item.inStock)
            {
                EncodedString = EncodedString + "s";        // 재고 있을 경우 's' 추가
            }
            if (EncodedString.Length > ItemQuoteTextConst.MAX_WIRE_LENGTH)
            {
                throw new IOException("Encoded length too long");
            }
            byte[] buf = encoding.GetBytes(EncodedString);
            return(buf);
        }
Example #2
0
        public override void OnTest(string[] args)
        {
            if (args.Length != 2)       // Test for correct # of args
            {
                throw new ArgumentException("Parameters: <Destination> <Port>");
            }
            String server   = args[0];              // 목적지 주소
            int    servPort = Int32.Parse(args[1]); // 목적지 포트

            // 서버의 해당 포트에 접속하는 소켓 객체를 생성한다.
            TcpClient     client    = new TcpClient(server, servPort);
            NetworkStream netStream = client.GetStream();

            ItemQuote quote = new ItemQuote(1234567890987654L, "5mm Super Widgets",
                                            100, 12999, true, false);
            // 텍스트 형태로 인코딩 한 가격 책정(quote) 정보를 전송한다.
            ItemQuoteEncoderText coder = new ItemQuoteEncoderText();

            byte[] codedQuote = coder.encode(quote);
            Console.WriteLine("Sending Text-Encoded Quote (" + codedQuote.Length + "bytes): ");
            Console.Write(quote);

            netStream.Write(codedQuote, 0, codedQuote.Length);

            // 이진 형태로 인코딩한 가격 책정 정보를 수신한다.
            ItemQuoteDecoder decoder       = new ItemQuoteDecoderBin();
            ItemQuote        receivedQuote = decoder.decode(client.GetStream());

            Console.WriteLine("Received Binary-Encode Quote: ");
            Console.WriteLine(receivedQuote);

            netStream.Close();
            client.Close();
        }
Example #3
0
        public override void OnTest(string[] args)
        {
            if (args.Length != 1)   // 파라미터의 개수 확인
            {
                throw new ArgumentException("Parameters: <Port>");
            }

            int port = Int32.Parse(args[0]);

            // 클라이언트의 연결 요청을 수락할 TCPListener 객체를 생성한다.
            TcpListener listener = new TcpListener(IPAddress.Any, port);

            listener.Start();

            TcpClient client = listener.AcceptTcpClient();      // 클라이언트 연결 요청을 수락한다.

            // 텍스트로 인코딩된 가격 책정 정보를 수신한다.
            ItemQuoteDecoder decoder = new ItemQuoteDecoderText();
            ItemQuote        quote   = decoder.decode(client.GetStream());

            Console.WriteLine("Received Text-Encoded Quote: ");
            Console.WriteLine(quote);

            // 가격 책정 정보에서 단가에 10센트를 추가한 후, 이진의 형태로 재전송한다.
            ItemQuoteEncoder encoder = new ItemQuoteEncoderBin();

            quote.unitPrice += 10;      // Add 10 cents to unit price
            Console.WriteLine("Sending (binary)...");
            byte[] bytesToSend = encoder.encode(quote);
            client.GetStream().Write(bytesToSend, 0, bytesToSend.Length);

            client.Close();
            listener.Stop();
        }
        public byte[] encode(ItemQuote item)
        {
            MemoryStream mem    = new MemoryStream();
            BinaryWriter output = new BinaryWriter(new BufferedStream(mem));

            output.Write(IPAddress.HostToNetworkOrder(item.itemNumber));
            output.Write(IPAddress.HostToNetworkOrder(item.quantity));
            output.Write(IPAddress.HostToNetworkOrder(item.unitPrice));

            byte flags = 0;

            if (item.discounted)
            {
                flags |= ItemQuoteBinConst.DISCOUNT_FLAG;
            }
            if (item.inStock)
            {
                flags |= ItemQuoteBinConst.IN_STOCK_FLAG;
            }
            output.Write(flags);

            byte[] encodedDesc = encoding.GetBytes(item.itemDescription);
            if (encodedDesc.Length > ItemQuoteBinConst.MAX_DESC_LEN)
            {
                throw new IOException("Item Description exceeds encoded length limit");
            }
            output.Write((byte)encodedDesc.Length);
            output.Write(encodedDesc);

            output.Flush();

            return(mem.ToArray());
        }
Example #5
0
        public override void OnTest(string[] args)
        {
            if (args.Length != 1 && args.Length != 2)   // 파라미터의 개수 확인
            {
                throw new ArgumentException("Parameters: <Port> [<encoding>]");
            }

            int port = Int32.Parse(args[0]);        // 수신 포트

            UdpClient client = new UdpClient(port); // 수신을 위한 UDP 소켓

            byte[]     packet           = new byte[ItemQuoteTextConst.MAX_WIRE_LENGTH];
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);

            packet = client.Receive(ref remoteIPEndPoint);

            ItemQuoteDecoderText decoder = (args.Length == 2) ? // 인코딩 확인
                                           new ItemQuoteDecoderText(args[1]) : new ItemQuoteDecoderText();

            ItemQuote quote = decoder.decode(packet);

            Console.WriteLine(quote);

            client.Close();
        }
        public override void OnTest(string[] args)
        {
            if (args.Length != 2)   // 파라미터 개수 확인
            {
                throw new ArgumentException("Parameter(s): <Multicast Addr> <Port>");
            }
            IPAddress address = IPAddress.Parse(args[0]);       // 멀티캐스트 주소

            if (!MCIPAddress.isValid(args[0]))
            {
                throw new ArgumentException("Valid MC addr: 224.0.0.0 - 239.255.255.255");
            }
            int    port = Int32.Parse(args[1]);         // 멀티캐스트 포트
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                                     ProtocolType.Udp); // 멀티캐스트 메시지 수신 소켓

            // 주소 재사용 옵션을 설정한다.
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            // IPEndPoint 인스턴스를 생성하여 이에 결합한다.
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);

            sock.Bind(ipep);

            // 멀티캐스트 그룹 멤버쉽에 가입한다.
            sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                                 new MulticastOption(address, IPAddress.Any));
            IPEndPoint receivePoint     = new IPEndPoint(IPAddress.Any, 0);
            EndPoint   tempReceivePoint = (EndPoint)receivePoint;

            // 데이터그램을 생성하고 수신한다.
            byte[] packet = new byte[ItemQuoteTextConst.MAX_WIRE_LENGTH];
            int    length = sock.ReceiveFrom(packet, 0, ItemQuoteTextConst.MAX_WIRE_LENGTH,
                                             SocketFlags.None, ref tempReceivePoint);

            ItemQuoteDecoderText decoder = new ItemQuoteDecoderText();      // 텍스트 디코딩 작업
            ItemQuote            quote   = decoder.decode(packet);

            Console.WriteLine(quote);

            // 그룹 멤버쉽을 탈퇴한다.
            sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership,
                                 new MulticastOption(address, IPAddress.Any));
            sock.Close();
        }
        public override void OnTest(string[] args)
        {
            if (args.Length < 2 || args.Length > 3) // 파라미터 개수 확인
            {
                throw new ArgumentException("Parameter(s): <Multicast Addr> <Port> [<TTL>]");
            }
            IPAddress destAddr = IPAddress.Parse(args[0]);      // 목적지 주소

            if (!MCIPAddress.isValid(args[0]))
            {
                throw new ArgumentException("Valid MC addr: 224.0.0.0 - 239.255.255.255");
            }
            int destPort = Int32.Parse(args[1]); // 목적지 포트
            int TTL;                             // 데이터그램이 유효한 시간(TTL)

            if (args.Length == 3)
            {
                TTL = Int32.Parse(args[2]);
            }
            else
            {
                TTL = 1;        // 기본 TTL 수치
            }
            ItemQuote quote = new ItemQuote(123456789098765L, "5mm Super Widgets",
                                            1000, 12999, true, false);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //TTL 수치를 설정한다.
            sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, TTL);

            ItemQuoteEncoderText encoder = new ItemQuoteEncoderText();  // 텍스트 인코딩

            byte[] codedQuote = encoder.encode(quote);

            // IP 엔드포인트 클래스 인스턴스를 생성한다.
            IPEndPoint ipep = new IPEndPoint(destAddr, destPort);

            // 패킷을 생성하고 전송한다.
            sock.SendTo(codedQuote, 0, codedQuote.Length, SocketFlags.None, ipep);
            sock.Close();
        }
Example #8
0
        public override void OnTest(string[] args)
        {
            if (args.Length != 2 && args.Length != 3)    // 파라미터 개수 확인
            {
                throw new ArgumentException("Parameter(s): <Destination>" + " <Port> [<encoding>]");
            }
            String server   = args[0];                  // 목적지 주소
            int    destPort = Int32.Parse(args[1]);     // 목적지 포트

            ItemQuote quote = new ItemQuote(1234567890987654L, "5mm Super Widgets",
                                            100, 12999, true, false);

            UdpClient client = new UdpClient();     // 전송을 위한 UDP 소켓

            ItemQuoteEncoder encoder = (args.Length == 3) ?
                                       new ItemQuoteEncoderText(args[2]) : new ItemQuoteEncoderText();

            byte[] codedQuote = encoder.encode(quote);

            client.Send(codedQuote, codedQuote.Length, server, destPort);

            client.Close();
        }