C# socket beginAccept


服務端:
    需要增加的命名空間:
using System.Threading;
using System.Net;
using System.Net.Sockets;
    以下是具體實現。
C# code復制代碼
namespace TCPServer
{
        public partial class Form1 : Form
        {
                public Form1()
                {
                        InitializeComponent();
                       
                }
                public bool btnstatu = true;    //開始停止服務按鈕狀態
                public Thread myThread;             //聲明一個線程實例
                public Socket newsock;                //聲明一個Socket實例
                public Socket Client;                  
                public IPEndPoint localEP;       
                public int localPort;
                public bool m_Listening;
                //用來設置服務端監聽的端口號
                public int setPort                       
                {
                        get { return localPort; }
                        set { localPort = value; }
                }
               
                //用來往richtextbox框中顯示消息
                public void showClientMsg(string msg)
                {
                        showClientMsg(msg+"\r\n");
                }
                //監聽函數
                public void Listen()
                {     //設置端口
                        setPort=int.Parse(serverport.Text.Trim());
                        //初始化SOCKET實例
                        newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        //初始化終結點實例
                        localEP=new IPEndPoint(IPAddress.Any,setPort);
                        try
                        {
                                //綁定
                                newsock.Bind(localEP);
                                //監聽
                                newsock.Listen(10);
                                //用於設置按鈕狀態
                                m_Listening = true;
                                //開始接受連接,異步。
                                newsock.BeginAccept(new AsyncCallback(OnConnectRequest), newsock);
                         }
                        catch (Exception ex)
                        {
                                showClientMsg(ex.Message);
                        }

                }
                //當有客戶端連接時的處理
                public void OnConnectRequest(IAsyncResult ar)
                {
                     //初始化一個SOCKET,用於其它客戶端的連接
                        Socket server1 = (Socket)ar.AsyncState;
                        Client = server1.EndAccept(ar);
                        //將要發送給連接上來的客戶端的提示字符串
                        string strDateLine = "Welcome here";
                        Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine);
                        //將提示信息發送給客戶端
                        Client.Send(byteDateLine, byteDateLine.Length, 0);
                        //等待新的客戶端連接
                        server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);
                        while (true)
                        {
                                int recv = Client.Receive(byteDateLine);
                                string stringdata = Encoding.ASCII.GetString(byteDateLine, 0, recv);
                                DateTimeOffset now = DateTimeOffset.Now;
                                //獲取客戶端的IP和端口
                                string ip = Client.RemoteEndPoint.ToString();
                                if (stringdata == "STOP")
                                {
                                        //當客戶端終止連接時
                                        showinfo.AppendText(ip+"已從服務器斷開");
                                        break;  
                                }
                                //顯示客戶端發送過來的信息
                                showinfo.AppendText(ip + "    " + now.ToString("G") + "     " + stringdata + "\r\n");                          
                        }
                                              
                }
            //開始停止服務按鈕
                private void startService_Click(object sender, EventArgs e)
                {
                        //新建一個委托線程
                        ThreadStart myThreadDelegate = new ThreadStart(Listen);
                        //實例化新線程
                        myThread = new Thread(myThreadDelegate);
                          
                        if (btnstatu)
                        {
                              
                                myThread.Start();
                                statuBar.Text = "服務已啟動,等待客戶端連接";
                                btnstatu = false;
                                startService.Text = "停止服務";
                        }
                        else
                        {
                                //停止服務(功能還有問題,無法停止)
                                m_Listening = false;
                                newsock.Close();
                                myThread.Abort();
                                showClientMsg("服務器停止服務");
                                btnstatu = true;
                                startService.Text = "開始服務";
                                statuBar.Text = "服務已停止";
                                m_Listening = false;
                        }
                          
                }
                //窗口關閉時中止線程。
                private void Form1_FormClosing(object sender, FormClosingEventArgs e)
                {
                        if (myThread != null)
                        {
                                myThread.Abort();
                        }
                }
        }
}

客戶端:
C# code復制代碼
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;
using System.Net.Sockets;
using System.Threading;
namespace TCPClient
{
        public partial class Form1 : Form
        {
                public Socket newclient;
                public bool Connected;
                public Thread myThread;
                public delegate void MyInvoke(string str);
                public Form1()
                {
                        InitializeComponent();
                       
                }
                public void Connect()
                {
                        byte[] data = new byte[1024];
                        newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        string ipadd = serverIP.Text.Trim();
                        int port = Convert.ToInt32(serverPort.Text.Trim());
                        IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);
                        try
                        {
                                newclient.Connect(ie);
                                connect.Enabled = false;
                                Connected = true;
                              
                        }
                        catch(SocketException e)
                        {
                                MessageBox.Show("連接服務器失敗    "+e.Message);
                                return;
                        }
                        ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
                        myThread = new Thread(myThreaddelegate);
                        myThread.Start();

                }
                public void ReceiveMsg()
                {
                        while (true)
                        {
                                byte[] data = new byte[1024];
                                int recv = newclient.Receive(data);
                                string stringdata = Encoding.UTF8.GetString(data, 0, recv);
                                showMsg(stringdata + "\r\n");
                                //receiveMsg.AppendText(stringdata + "\r\n");
                        }
                }
                public void showMsg(string msg)
                {
                        {
                        //在線程里以安全方式調用控件
                        if (receiveMsg.InvokeRequired)
                        {
                                MyInvoke _myinvoke = new MyInvoke(showMsg);
                                receiveMsg.Invoke(_myinvoke, new object[] { msg });
                        }
                        else
                        {
                                receiveMsg.AppendText(msg);
                        }
                }
                }
              

                private void SendMsg_Click(object sender, EventArgs e)
                {
                        int m_length = mymessage.Text.Length;
                        byte[] data=new byte[m_length];
                        data = Encoding.UTF8.GetBytes(mymessage.Text);
                        int i = newclient.Send(data);
                        showMsg("我說:" + mymessage.Text + "\r\n");
                        //receiveMsg.AppendText("我說:"+mymessage.Text + "\r\n");
                        mymessage.Text = "";
                        //newclient.Shutdown(SocketShutdown.Both);
                }

                private void connect_Click(object sender, EventArgs e)
                {
                        Connect();
                }
               
        }來自於:http://hi.baidu.com/wuyunju/item/006610520eb58e968c12eda0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM