C# SOCKET 编程实例

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);
           
        }
    }
}

posted on 2011-02-11 14:16  和轩僮  阅读(1070)  评论(2编辑  收藏  举报

导航