C# 服务端编程监听IP和端口号

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;

namespace MOSendNotificationRestServer
{
    public partial class Form1 : Form
    {
        //monitor
        private TcpListener Listener;
        private string mServerAdress;
        private Int32 mServerPort;

        public Form1()
        {
            InitializeComponent();
        }

        private void startBTT_Click(object sender, EventArgs e)
        {
            try
            {
                mServerAdress = IPTT.Text.ToString();
                mServerPort = int.Parse(PORTTT.Text.ToString());
                // monitor
                Listener = new TcpListener(IPAddress.Parse(mServerAdress), mServerPort);
                // start monitor
                Listener.Start();

                MessageBox.Show("start port monitor success");
                //recevice client's any request messages.
                Socket mySocket = Listener.AcceptSocket();

                Byte[] bReceive = new Byte[1024];

                int i = mySocket.Receive(bReceive, bReceive.Length, 0);
 
                string sBuffer = Encoding.UTF8.GetString(bReceive);

                ServerTT.Text = sBuffer.ToString();

                //if client request method is post.
                if (sBuffer.Substring(0, 4) == "POST")
                {
                    int iTotBytes = 0;
                    //you must create a file to set server responses.

                   //从本地文件中读取设定返回响应的文件内容
                    string sPhysicalFilePath = "d:\\temp.log";          
                    string sResponse = "";
                    //from localpath to read response message header content
                    FileStream fs = new FileStream(sPhysicalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    BinaryReader reader = new BinaryReader(fs);
                    byte[] bytes = new byte[fs.Length];
                    int read;
                    while ((read = reader.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        sResponse = sResponse + Encoding.UTF8.GetString(bytes, 0, read);
                        iTotBytes = iTotBytes + read;
                    }

                    reader.Close();

                    fs.Close();

                    mySocket.Send(bytes, bytes.Length, 0);

                    mySocket.Close();
                    // stop monitor
                    Listener.Stop();

                    MessageBox.Show("stop port monitor success");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("a error occur:" + ex.Message);
            }


        }

       
    }
}

 

 

你可能感兴趣的:(C#网络编程)