SuperSocket 入门,实现客户端和服务端消息互发

来源:互联网 发布:什么叫网络投资 编辑:程序博客网 时间:2024/05/16 02:14

运行出来效果如下:

服务端:


客户端:



第一步,使用SuperSocket创建一个服务端

a.引入需要dll文件,由于supersocket使用到了log4,所以在这儿也需要引用log4net.dll

添加项目引用即可


b.创建一个server


在Program.cs中 设置程序运行的窗体,在窗体的load事件中启动socket服务。

code:

/// <summary>
        /// 窗体初始化加载,启动socket服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {


            //配置
            ServerConfig serverConfig = new ServerConfig();
            serverConfig.Port = 8080;//端口号
            serverConfig.Mode = SocketMode.Tcp;//设置为tcp服务器

            //设置服务配置
            if (!appServer.Setup(serverConfig))
            {
                System.Windows.Forms.MessageBox.Show("开启服务器失败");
                return;
            }


            //启动服务
            if (!appServer.Start())
            {
                System.Windows.Forms.MessageBox.Show("开启服务器失败");
                return;
            }


            //注册监听事件

            appServer.NewSessionConnected += AppServer_NewSessionConnected; //新的客户端连接事件
            appServer.NewRequestReceived += AppServer_NewRequestReceived;//接收到客户端消息事件
            appServer.SessionClosed += AppServer_SessionClosed;//连接关闭触发事件
        }

到此,就启动了一个简单的tcp socket 服务,接下来,启动一个客户端进行连接

code:

//客户端对象

AsyncTcpSession tcpClient = null;

/// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {


            string ipAddress = this.ipTextBox.Text.ToString();
            string port = this.portTextBox.Text.ToString();
            tcpClient = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(ipAddress), int.Parse(port)));
            tcpClient.Connect();
            tcpClient.DataReceived += TcpClient_DataReceived;
            tcpClient.Error += TcpClient_Error;
            tcpClient.Closed += TcpClient_Closed;
        }

客户端连接成功,给服务器发送消息

if (tcpClient != null)
  {

if (tcpClient.IsConnected)

{

string message = this.sendMessageTextBox.Text.ToString() + "\r\n";
                        byte[] data = Encoding.UTF8.GetBytes(message);
                        tcpClient.Send(data, 0, data.Length);

}

至此,就完成了服务器和客户端的简单搭建,刚入c#大法,也是第一次写文章,希望大家多多指点。

源码链接:http://download.csdn.net/download/weixin_35196633/10151210



阅读全文
0 0
原创粉丝点击