Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9309

cscの作法 その36

$
0
0

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

webserver立てて、生httpを取得せよ。

サンプルコード

using System;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;


class form1: Form {
    form1() {
        Text = "server";
        ClientSize = new Size(200, 200);
        Button btn1 = new Button();
        btn1.Location = new Point(50, 50);
        btn1.Text = "test";
        btn1.Click += btn1_Click;
        Controls.AddRange(new Control[] {
            btn1
        });
    }
    void btn1_Click(object sender, System.EventArgs e) {
        TcpListener server = null;
        try
        {
            Int32 port = 80;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            server = new TcpListener(localAddr, port);
            server.Start();
            Byte[] bytes = new Byte[4096];
            String html = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 64\r\n<!DOCTYPE html><html><body><h1>it's work!</h1></body></html>\r\n";
            String data = null;
            Console.Write(">Waiting for a connection... ");
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine(">Connected!");
            NetworkStream stream = client.GetStream();
            int i;
            i = stream.Read(bytes, 0, bytes.Length);
            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine(">Received: {0}", data);
            byte[] msg = System.Text.Encoding.ASCII.GetBytes(html);
            stream.Write(msg, 0, msg.Length);
            Console.WriteLine(">Sent: {0}", html);
            client.Close();
        }
        catch(SocketException d)
        {
            Console.WriteLine("SocketException: {0}", d);
        }
        finally
        {
             server.Stop();
        }
        Console.WriteLine(">ok");
    }
    [STAThread]
    public static void Main() {
        Application.Run(new form1());
    }
}





以上。


Viewing all articles
Browse latest Browse all 9309