服务端:
    需要增加的命名空间:
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

C# socket beginAccept的更多相关文章

  1. C#中使用Socket实现简单Web服务器

    上一篇博客中介绍了怎样使用socket访问web服务器.关键有两个: 熟悉Socket编程: 熟悉HTTP协议. 上一篇主要是通过socket来模拟浏览器向(任何)Web服务器发送(HTTP)请求,重 ...

  2. C#中使用Socket请求Web服务器过程

    最开始我们需要明白一件事情,因为这是这篇文章的前提: HTTP协议只是一个应用层协议,它底层是通过TCP进行传输数据的.因此,浏览器访问Web服务器的过程必须先有“连接建立”的发生. 而有人或许会问: ...

  3. Socket实现异步通信

    private static void RecVing(IAsyncResult Result) {     //通过 result 获取socket.在这个socket上你启动了BeginAccep ...

  4. 详谈socket请求Web服务器过程

    最开始我们需要明白一件事情,因为这是这篇文章的前提: HTTP协议只是一个应用层协议,它底层是通过TCP进行传输数据的.因此,浏览器访问Web服务器的过程必须先有“连接建立”的发生. 而有人或许会问: ...

  5. 以C#编写的Socket服务器的Android手机聊天室Demo

    内容摘要 1.程序架构 2.通信协议 3.服务器源代码 4.客户端源代码 5.运行效果 一.程序架构 在开发一个聊天室程序时,我们可以使用Socket.Remoting.WCF这些具有双向通信的协议或 ...

  6. Socket异步通信学习二

    接下来是服务器部分,采用异步模式,新建了一个AsynServer类,用于存放socket服务器代码,主要有4个方法: 有一个全局socket,下面四个方法中都用到. Socket socket = n ...

  7. .net平台下socket异步通讯

    1,首先添加两个windows窗体项目,一个作为服务端server,一个作为客户端Client 2,然后添加服务端代码,添加命名空间,界面上添加TextBox控件 using System.Net; ...

  8. 一个Socket数据处理模型

    Socket编程中,如何高效地接收和处理数据,这里介绍一个简单的编程模型. Socket索引 - SocketId 在给出编程模型之前,先提这样一个问题,程序中如何描述Socket连接? 为什么这么问 ...

  9. 利用Socket实现的两个程序的通信

    写的也很简单,自己觉得挺有意思了 程序如图 主要代码 public class Message { Form1 mainfrom = null; public Message() { } public ...

随机推荐

  1. java.sql.SQLException:错误 The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.

    错误 方法 添加后面的内容即可

  2. react入门安装

    react的入门安装 1.react的适用方法有两种,其一是依赖在线的cdn地址: https://reactjs.org/docs/cdn-links.html 官方给的cdn地址如下 <sc ...

  3. jquery06 jQuery.extend 给jQuery函数添加、继承 静态方法

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  4. 31.Intellij idea 的maven项目如何通过maven自动下载jar包

    转自:https://blog.csdn.net/u012851114/article/details/81872981 maven项目自动加载jar包 所需工具如下: Intellij IDEA 1 ...

  5. 56.lambda表达式与绑定以及伪函数和绑定

    #include <iostream> #include <functional> using namespace std; using namespace std::plac ...

  6. BZOJ 1232 Kruskal

    思路: 跟昨天的考试题特别像-.. 就是裸的Kruskal 把边权设为连接的两个点的点权之和加上边权*2 搞定 //By SiriusRen #include <cstdio> #incl ...

  7. Day5网络流

    算法 无源汇上下界可行流 先强制流过l的流量 从s到每个正权点连流量为l的流量 从每个负权点向t连-l的流量 如果容量为0,则不连边 有源汇上下界最大流 去掉下界 先求出可行流 再求S到T的最大流 有 ...

  8. vim--学习之emmet插件前端开发

    Emmet 在vim的使用: 1.嵌套 <ctr+y>+,(ctr+y+逗号三者的组合键,ctr+y一起按在按逗号)相当于Ememet中的Tab键. 2.内容的包围: 写好内容,退出编辑模 ...

  9. python 中文文档地址总结

    sqlalchemy: https://www.imooc.com/article/details/id/22343

  10. UVALive 5292 Critical Links

    Critical Links Time Limit: 3000ms Memory Limit: 131072KB This problem will be judged on UVALive. Ori ...