C# SOCKET 編程執行個體

來源:互聯網
上載者:User

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace test4_2
{
    public partial class Form1 : Form
    {
        Socket connectSocket;
        //Socket client;
        byte[] bytes = new byte[1024];
        delegate void listboxDel(string s);
        listboxDel listboxdel;
        public Form1()
        {
            InitializeComponent();
            textBoxContent.Focus();
            listboxdel = new listboxDel(listbox);
            //為串連指派線程
            Thread threadConnect = new Thread(new ThreadStart(Connect));
            threadConnect.Start();
         
        }
        public void listbox(string str)
        {
            listBox1.Items.Add(str);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            listBox1.ClearSelected();
        }

        //串連方法
        public void Connect()
        {

            try
            {

                //建立串連socket
                connectSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                //開始非同步串連
                connectSocket.BeginConnect(IPAddress.Parse("172.16.94.152"),
                                    82,
                                    new AsyncCallback(ConnectCallback),  //定義回呼函數代理
                                    connectSocket);                      //傳遞給回呼函數的狀態
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        //串連方法的回呼函數
        private  void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                //從傳遞的狀態中擷取通訊端,建立一個用戶端通訊端
                Socket client = (Socket)ar.AsyncState;

                //完成掛起的串連操作
                client.EndConnect(ar);
                listBox1.Invoke(listboxdel, "串連伺服器成功,可以開始通話!");
                client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        public void receivecallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                int length = client.EndReceive(ar);
                listBox1.Invoke(listboxdel, Encoding.UTF8.GetString(bytes, 0, length));
                client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
            }
            catch
            {
            }

        }
        //發送方法
        private void Send(String data)
        {
            //使用ASCII轉換字串為位元組序列
            byte[] byteData = Encoding.UTF8.GetBytes(data);   //將字串轉換成位元組序列

            //開始向遠端裝置發送資料
            connectSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
                new AsyncCallback(SendCallback), connectSocket);
        }

        //發送方法的回呼函數
        private  void SendCallback(IAsyncResult ar)
        {
            try
            {
                //從傳遞的狀態中擷取通訊端,建立一個用戶端通訊端
                Socket client = (Socket)ar.AsyncState;

                //結束非同步資料轉送操作,返回傳輸的位元組數
                int bytesSent = client.EndSend(ar);
                listBox1.Invoke(listboxdel, textBoxUser.Text +":"+ textBoxContent.Text);
              
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

     

        private void buttonSend_Click(object sender, EventArgs e)
        {

            Send(textBoxUser.Text+":"+textBoxContent.Text);
           
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.