首页 > 其他分享 >Socket示例

Socket示例

时间:2022-10-01 03:33:18浏览次数:41  
标签:tcpClient Socket 示例 Text void System private using

服务端代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace SocketServerChatRoom
{
    public partial class FormServer : Form
    {
        public FormServer()
        {
            InitializeComponent();
        }

        private Socket tcpServer;
        private Dictionary<string, Socket> onlineList = new Dictionary<string, Socket>();
        private string CurrentTime
        {
            get
            {
                return DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
            }
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            string ip = this.txtIP.Text;
            int port = int.Parse(this.txtPort.Text);
            this.tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
            try
            {
                this.tcpServer.Bind(endPoint);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("服务器开启失败:{0}", ex.Message));
                return;
            }

            this.tcpServer.Listen(10);

            this.ShowMsg("服务器开启成功!");

            Task.Run(() => this.ListenConnection());

            this.btnStartServer.Enabled = false;

        }

        /// <summary>
        /// 监听连接
        /// </summary>
        private void ListenConnection()
        {
            while (true)
            {
                Socket tcpClient = this.tcpServer.Accept();
                string clientIP = tcpClient.RemoteEndPoint.ToString();

                this.AddOnLine(tcpClient, true);

                this.ShowMsg(clientIP + " 上线了!");

                Task.Run(() => this.ReceiveMsg(tcpClient));
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="tcpClient"></param>
        private void ReceiveMsg(Socket tcpClient)
        {
            while (true)
            {
                //定义2M的缓冲区
                byte[] buffer = new byte[1024 * 1024 * 2];
                int length = -1;
                try
                {
                    length = tcpClient.Receive(buffer);
                }
                catch
                {
                    this.AddOnLine(tcpClient, false);
                    break;
                }
                if (length == 0)
                {
                    this.AddOnLine(tcpClient, false);
                    break;
                }
                if (length > 0)
                {
                    string msg = Encoding.UTF8.GetString(buffer, 0, length).Trim();
                    this.ShowMsg(tcpClient.RemoteEndPoint.ToString() + "对你说:\r\n" + msg);
                }
            }
        }

        private void AddOnLine(Socket tcpClient, bool isAdd)
        {
            string clientIP = tcpClient.RemoteEndPoint.ToString();
            if (isAdd)
            {
                this.onlineList.Add(clientIP, tcpClient);
            }
            else
            {
                this.onlineList.Remove(clientIP);
            }
            Invoke(new Action(() =>
            {
                if (isAdd)
                {
                    this.listOnLine.Items.Add(clientIP);
                }
                else
                {
                    this.listOnLine.Items.Remove(clientIP);
                }
            }
            ));
        }

        private void ShowMsg(string msg)
        {
            Invoke(new Action(() =>
            {
                this.txtMsg.AppendText(this.CurrentTime + msg + Environment.NewLine);
            }
            ));
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            if (this.listOnLine.SelectedItems.Count > 0)
            {
                foreach (string item in this.listOnLine.SelectedItems)
                {
                    if (this.onlineList.ContainsKey(item))
                    {
                        this.onlineList[item].Send(Encoding.UTF8.GetBytes(this.txtSendMsg.Text));
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择要发送的对象!");
            }
        }

        private void btnSendMsgAll_Click(object sender, EventArgs e)
        {
            foreach (string item in this.listOnLine.Items)
            {
                if (this.onlineList.ContainsKey(item))
                {
                    this.onlineList[item].Send(Encoding.UTF8.GetBytes(this.txtSendMsg.Text));
                }
            }
        }

        private void btnClient_Click(object sender, EventArgs e)
        {
            FormClient formClient = new FormClient();
            formClient.Show();
        }
    }
}

客户端代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketServerChatRoom
{
    public partial class FormClient : Form
    {
        public FormClient()
        {
            InitializeComponent();
        }

        #region Socket-Client

        //创建Socket
        private Socket tcpClient;

        //创建取消数据源
        private CancellationTokenSource cts = new CancellationTokenSource();

        #region btnConnect_Click
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (this.btnConnect.Text == "连接")
            {
                string ip = this.txtIP.Text;
                int port = int.Parse(this.txtPort.Text);
                this.tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                EndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                try
                {
                    this.tcpClient.Connect(endPoint);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                this.btnConnect.Text = "断开";
                this.btnSendMsg.Enabled = true;

                Task.Run(new Action(() =>
                {
                    this.ReceiveMsg();
                }));

            }
            else
            {
                this.tcpClient?.Close();
                //this.cts.Cancel();
                this.btnConnect.Text = "连接";
                this.btnSendMsg.Enabled = false;
            }

        }
        #endregion

        #region ReceiveMsg
        private void ReceiveMsg()
        {
            while (!cts.IsCancellationRequested)
            {
                byte[] buffer = new byte[1024 * 10];
                int length = -1;
                try
                {
                    length = this.tcpClient.Receive(buffer, SocketFlags.None);
                }
                catch (Exception)
                {
                    break;
                }

                if (length > 0)
                {
                    string msg = Encoding.UTF8.GetString(buffer, 0, length).Trim();
                    this.txtMsg.Text += msg + "\r\n";
                }
            }
        }

        #endregion

        #endregion

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(this.txtMsg.Text);

            this.tcpClient.Send(buffer);
        }

        private void FormClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.cts.Cancel();
            if(this.tcpClient != null)
                this.tcpClient.Close();
        }
    }
}

 

标签:tcpClient,Socket,示例,Text,void,System,private,using
From: https://www.cnblogs.com/davidkam/p/16746667.html

相关文章

  • C++_Windows Socket 学习记录_01
    主要实现服务器-服务器传输消息Server.cpp#include<stdio.h>#include<stdlib.h>#include<WinSock2.h>#include<iostream>#pragmacomment(lib,"ws2_32.lib")us......
  • socket,端口,进程问答(收集整理)
    一、一台计算机有几个端口,分别是什么?作用呢?端口可分为3大类:1)公认端口(WellKnownPorts):从0到1023,它们紧密绑定于一些服务。通常这些端口的通讯明确表明了某种服务的协议。......
  • 有了 HTTP 协议,为什么还需要 Websocket?
    WebSocket是一种基于TCP连接上进行全双工通信的协议,相对于HTTP这种非持久的协议来说,WebSocket是一个持久化网络通信的协议。它不仅可以实现客户端请求服务器,同时可以......
  • 0069-Tui-综合示例(一)
    环境Time2022-08-23Rust1.63.0Tui0.19.0前言说明参考:https://github.com/fdehau/tui-rs/tree/master/examples/demo目标实现tui-rs的综合示例程序,读取命令......
  • 0070-Tui-综合示例(二)
    环境Time2022-08-23Rust1.63.0Tui0.19.0前言说明参考:https://github.com/fdehau/tui-rs/tree/master/examples/demo目标实现tui-rs的综合示例程序,终端的开......
  • 0071-Tui-综合示例(三)
    环境Time2022-08-23Rust1.63.0Tui0.19.0前言说明参考:https://github.com/fdehau/tui-rs/tree/master/examples/demo目标实现tui-rs的综合示例程序,应用数据......
  • 0072-Tui-综合示例(四)
    环境Time2022-08-23Rust1.63.0Tui0.19.0前言说明参考:https://github.com/fdehau/tui-rs/tree/master/examples/demo目标实现tui-rs的综合示例程序。定义布......
  • 0061-Tui-迷你图示例
    环境Time2022-08-16Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/sparkline.rs目标使用tui-rs显示迷你图。生......
  • 0064-Tui-图表示例
    环境Time2022-08-16Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/chart.rs目标使用tui-rs显示图表。常量数据......
  • 0065-Tui-Canvas 示例
    环境Time2022-08-17Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/canvas.rs目标使用tui-rs显示Canvas。定义......