Socket 通訊

1 篇文章 / 0 new
author
Socket 通訊
public partial class SocketForm : Form
{
    private Socket socket;
    private Thread thread;
 
    public SocketForm()
    {
        InitializeComponent();
    }
    //
    private delegate void textCallback(RichTextBox rt, string myStr);
    private void setText(RichTextBox rt, string text)
    {
        if (this.rtRecTxt.InvokeRequired)
        {
            textCallback d = new textCallback(setText);
            this.Invoke(d, new object[] { rt, text });
        }
        else
        {
            addLine(rt,text);
        }
    }
    private void receive()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(this.tbLocalIP.Text), Int32.Parse(this.tbLocalPort.Text));
        socket.Bind(endPoint);
        socket.Listen(10);//10 為最多可等候的連線數
        //thread 程序中不能 call UI 元件
        //方法一: 除非設定 Form.CheckForIllegalCrossThreadCalls = false;
        //addLine(rtRecTxt, "監聽中...");            
        //方法二: 使用 委派 方式
        setText(rtRecTxt, "監聽中...");         
        while(true){
            Socket theSocket = socket.Accept();
            byte[] messageByte = new Byte[64];
            theSocket.Receive(messageByte);
            string readMessage = System.Text.Encoding.BigEndianUnicode.GetString(messageByte);
            this.rtRecTxt.AppendText(readMessage);
        }
    }
 
    private void btnStart_Click(object sender, EventArgs e)
    {
        try
        {
            IPAddress.Parse(this.tbLocalIP.Text);
            Int32.Parse(this.tbLocalPort.Text);
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
            return;
        }
        if ((thread != null) && (thread.ThreadState == ThreadState.Running))
        {
            MessageBox.Show("已在監聽中...");
            return;
        }
        try {
            thread = new Thread(new ThreadStart(receive));
            thread.Start();
            addLine(rtRecTxt, "啟動中");
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
        }
    }
 
    private void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            IPAddress.Parse(this.tbRemoteIP.Text);
            Int32.Parse(this.tbRemotePort.Text);
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString());
            return;
        }
        if ((thread == null) || (thread.ThreadState != ThreadState.Running))
        {
            MessageBox.Show("請先啟動監聽.");
            return;
        }
        Socket theSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        theSocket.Connect(this.tbRemoteIP.Text, Int32.Parse(this.tbRemotePort.Text));
        string send = this.rtSendTxt.Text + "\r\n";//不可以用 Environment.NewLine
        byte[] messageByte = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
        theSocket.Send(messageByte);
        theSocket.Shutdown(SocketShutdown.Both);
        theSocket.Close();
    }
 
    private void btnStop_Click(object sender, EventArgs e)
    {
        if ((thread == null) || (thread.ThreadState != ThreadState.Running))
        {   //MessageBox.Show("未啟動監聽.");
            return;
        }
        if ((thread != null) && (thread.ThreadState == ThreadState.Running))
            thread.Abort();
        if (socket != null)
            socket.Close();
        addLine(rtRecTxt,"停止監聽");
    }
    private void addLine(RichTextBox tb, string data, bool newLine = true)
    {
        tb.AppendText(data + Environment.NewLine);
    }
 
    private void SocketForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        btnStop_Click(btnStop, null);
    }
}
Free Web Hosting