C#用websocket实现简易聊天功能(客户端)

本文实例为大家分享了C#用websocket实现简易聊天功能的具体代码,供大家参考,具体内容如下

前言

使用C#语言进行开发,基于.NET FrameWork4
功能包含群聊,和私聊
参考C# 利用websocket实现简易聊天功能——服务端

界面

界面设计代码

namespace chat_client
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.buttonSend = new System.Windows.Forms.Button();
            this.textBoxMsg = new System.Windows.Forms.TextBox();
            this.textBoxLog = new System.Windows.Forms.TextBox();
            this.buttonStart = new System.Windows.Forms.Button();
            this.labelPort = new System.Windows.Forms.Label();
            this.textBoxPort = new System.Windows.Forms.TextBox();
            this.labelIP = new System.Windows.Forms.Label();
            this.textBoxIP = new System.Windows.Forms.TextBox();
            this.labelName = new System.Windows.Forms.Label();
            this.textBoxName = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // buttonSend
            // 
            this.buttonSend.Location = new System.Drawing.Point(769, 504);
            this.buttonSend.Name = "buttonSend";
            this.buttonSend.Size = new System.Drawing.Size(99, 43);
            this.buttonSend.TabIndex = 15;
            this.buttonSend.Text = "发送";
            this.buttonSend.UseVisualStyleBackColor = true;
            this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
            // 
            // textBoxMsg
            // 
            this.textBoxMsg.Location = new System.Drawing.Point(36, 504);
            this.textBoxMsg.Name = "textBoxMsg";
            this.textBoxMsg.Size = new System.Drawing.Size(653, 25);
            this.textBoxMsg.TabIndex = 14;
            // 
            // textBoxLog
            // 
            this.textBoxLog.Location = new System.Drawing.Point(36, 78);
            this.textBoxLog.Multiline = true;
            this.textBoxLog.Name = "textBoxLog";
            this.textBoxLog.Size = new System.Drawing.Size(832, 406);
            this.textBoxLog.TabIndex = 13;
            // 
            // buttonStart
            // 
            this.buttonStart.Location = new System.Drawing.Point(726, 18);
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(142, 45);
            this.buttonStart.TabIndex = 12;
            this.buttonStart.Text = "连接服务器";
            this.buttonStart.UseVisualStyleBackColor = true;
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            // 
            // labelPort
            // 
            this.labelPort.AutoSize = true;
            this.labelPort.Location = new System.Drawing.Point(267, 33);
            this.labelPort.Name = "labelPort";
            this.labelPort.Size = new System.Drawing.Size(54, 15);
            this.labelPort.TabIndex = 11;
            this.labelPort.Text = "port:";
            // 
            // textBoxPort
            // 
            this.textBoxPort.Location = new System.Drawing.Point(327, 33);
            this.textBoxPort.Name = "textBoxPort";
            this.textBoxPort.Size = new System.Drawing.Size(100, 25);
            this.textBoxPort.TabIndex = 10;
            this.textBoxPort.Text = "6666";
            // 
            // labelIP
            // 
            this.labelIP.AutoSize = true;
            this.labelIP.Location = new System.Drawing.Point(74, 33);
            this.labelIP.Name = "labelIP";
            this.labelIP.Size = new System.Drawing.Size(31, 15);
            this.labelIP.TabIndex = 9;
            this.labelIP.Text = "IP:";
            // 
            // textBoxIP
            // 
            this.textBoxIP.Location = new System.Drawing.Point(125, 30);
            this.textBoxIP.Name = "textBoxIP";
            this.textBoxIP.Size = new System.Drawing.Size(100, 25);
            this.textBoxIP.TabIndex = 8;
            this.textBoxIP.Text = "127.0.0.1";
            // 
            // labelName
            // 
            this.labelName.AutoSize = true;
            this.labelName.Location = new System.Drawing.Point(473, 33);
            this.labelName.Name = "labelName";
            this.labelName.Size = new System.Drawing.Size(67, 15);
            this.labelName.TabIndex = 17;
            this.labelName.Text = "用户名:";
            // 
            // textBoxName
            // 
            this.textBoxName.Location = new System.Drawing.Point(546, 30);
            this.textBoxName.Name = "textBoxName";
            this.textBoxName.Size = new System.Drawing.Size(100, 25);
            this.textBoxName.TabIndex = 16;
            this.textBoxName.Text = "ant1";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(904, 564);
            this.Controls.Add(this.labelName);
            this.Controls.Add(this.textBoxName);
            this.Controls.Add(this.buttonSend);
            this.Controls.Add(this.textBoxMsg);
            this.Controls.Add(this.textBoxLog);
            this.Controls.Add(this.buttonStart);
            this.Controls.Add(this.labelPort);
            this.Controls.Add(this.textBoxPort);
            this.Controls.Add(this.labelIP);
            this.Controls.Add(this.textBoxIP);
            this.Name = "Form1";
            this.Text = "客户端";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button buttonSend;
        private System.Windows.Forms.TextBox textBoxMsg;
        private System.Windows.Forms.TextBox textBoxLog;
        private System.Windows.Forms.Button buttonStart;
        private System.Windows.Forms.Label labelPort;
        private System.Windows.Forms.TextBox textBoxPort;
        private System.Windows.Forms.Label labelIP;
        private System.Windows.Forms.TextBox textBoxIP;
        private System.Windows.Forms.Label labelName;
        private System.Windows.Forms.TextBox textBoxName;
    }
}

源代码

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

namespace chat_client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Socket clientSocket;
       

        private void buttonStart_Click(object sender, EventArgs e)
        {
            // 客户端连接服务器
            // 1 创建socket对象
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2、绑定ip和端口
            String ip = textBoxIP.Text;
            int port = Convert.ToInt32(textBoxPort.Text);
            try
            {
                clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
            }
            catch
            {
                MessageBox.Show("连接服务器失败");
            }
            //4、发送name
            byte[] data = Encoding.Default.GetBytes(textBoxName.Text);
            clientSocket.Send(data, 0, data.Length, SocketFlags.None);
            //3、接受消息
            Thread thread = new Thread(new ParameterizedThreadStart(recevie));
            thread.IsBackground = true;// 设置为后台线程
            thread.Start(clientSocket);
            buttonStart.Enabled = false;
        }

        private void recevie(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];
            String msg;
            int len = 0;
            while (true)
            {
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
                }
                catch
                {
                    stopConnect();//关闭连接
                    return;
                }

                if (len <= 0)
                {
                    //客户端正常退出
                    msg = String.Format("服务器{0}发送异常",
                   proxSocket.RemoteEndPoint.ToString());
                    stopConnect();//关闭连接
                    return;//结束当前接受客户端数据的异步线程
                }
                //显示消息
                msg = Encoding.Default.GetString(data, 0, len);
                showLog(msg);
            }
        }

        private void stopConnect()
        {
            try
            {
                if (clientSocket.Connected)
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close(100);
                }
            }
            catch
            {

            }
           
        }

        private void showLog(String msg)
        {
            if (textBoxLog.InvokeRequired)
            {
                //如果是跨线程访问
                textBoxLog.Invoke(new Action<String>(
                   s => {
                       this.textBoxLog.Text += msg + "\r\n";
                   }), msg);
            }
            else
            {
                this.textBoxLog.Text += msg;
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (clientSocket.Connected)
            {
                //先判断是否还有服务器处于连接状态
                byte[] data = Encoding.Default.GetBytes(textBoxMsg.Text);
                clientSocket.Send(data, 0, data.Length, SocketFlags.None);
                textBoxMsg.Text = "";
            }
            else
            {
                MessageBox.Show("与服务器断开连接");
            }
        }
    }
}

运行截图

打开多个运行程序,在项目生成可执行文件后,在项目文件目录下,找到bin\Debug
可以点击几个可执行程序

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#基于Socket实现多人聊天功能

    本文实例为大家分享了C#基于Socket实现多人聊天功能的具体代码,供大家参考,具体内容如下 服务器 服务器负责接受所有客户端发来的消息,和将接受到的问题群发到其他用户. 代码: using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatRoomService

  • C#用websocket实现简易聊天功能(服务端)

    C# 利用websocket实现简易聊天功能——服务端,供大家参考,具体内容如下 前言 使用C#语言进行开发,基于.NET FrameWork4 功能包含群聊,和私聊 界面 界面设计代码 namespace chat_server {     partial class Form1     {         /// <summary>         /// 必需的设计器变量.         /// </summary>         private System.Compo

  • C#使用Socket实现本地多人聊天室

    本文实例为大家分享了C#使用Socket实现本地多人聊天室的具体代码,供大家参考,具体内容如下 [脚本一:Server端] 使用本机地址:127.0.0.1 完整代码 using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;   namespace ConsoleApp1 {     p

  • 基于c#用Socket做一个局域网聊天工具

    程序设计成为简单的服务端和客户端之间的通信, 但通过一些方法可以将这两者进行统一起来, 让服务端也成为客户端, 让客户端也成为服务端, 使它们之间可以互相随时不间断的通信. 考虑到实现最原始的服务端和客户端之间的通信所需要的步骤对于写这样的程序是很有帮助的. 作为服务端, 要声明一个Socket A并绑定(Bind)某一个IP+这个IP指定的通信端口, 比如这个是127.0.0.1:9050, 然后开始监听(Listen), Listen可以监听来自多个IP传过来的连接请求, 具体可以同时连接几

  • c#基于WinForm的Socket实现简单的聊天室 IM

    1:什么是Socket 所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象. 一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制. 从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口. 2:客服端和服务端的通信简单流程 3:服务端Code: using System; using System.Collections.Generic; using Sys

  • C#制作简单的多人在线即时交流聊天室

    实现网页版的在线聊天室的方法有很多,在没有来到HTML5之前,常见的有:定时轮询.长连接+长轮询.基于第三方插件(如FLASH的Socket),而如果是HTML5,则比较简单,可以直接使用WebSocket,当然HTML5目前在PC端并没有被所有浏览器支持,所以我的这个聊天室仍是基于长连接+长轮询+原生的JS及AJAX实现的多人在线即时交流聊天室,这个聊天室其实是我上周周末完成的,功能简单,可能有些不足,但可以满足在线即时聊天需求,分享也是给大家提供一个思路,大家可以基于此来实现更好的在线即时聊

  • C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

    扩展: 由于server端是存储了所有server与client的连接对象,因此我们是可以基于此demo的基础上实现聊天系统: * 每当一个与用户发言时,是由server接收到的某个用户的发言信息的,此时服务器端可以通过循环发送该用户发送的信息给每个已经连接连接的用户(排除发送者). Server端代码: class Program { //创建一个和客户端通信的套接字 static Socket SocketWatch = null; //定义一个集合,存储客户端信息 static Dicti

  • C#使用WebSocket实现聊天室功能

    WebSocket介绍 WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. 在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道.两者之间就直接可以数据互相传送. 浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据. 当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发

  • 分享一个C#编写简单的聊天程序(详细介绍)

    引言 这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考.文章大体分为四个部分:程序的分析与设计.C#网络编程基础(篇外篇).聊天程序的实现模式.程序实现. 程序的分析与设计 1.明确程序功能 如果大家现在已经参加了工作,你的经理或者老板告诉你,"小王,我需要你开发一个聊天程序".那么接下来该怎么做呢?你是不是在脑子里有个雏形,然后就直接打开VS2005开始设计窗体,编写代码了呢?在开始之

  • C#使用Socket实现局域网聊天

    本文实例为大家分享了C#使用Socket实现局域网聊天的具体代码,供大家参考,具体内容如下 先运行一个java写的局域网聊天,效果图如下 后使用c#图形修改如下: C#代码: servlet服务端 using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using Sys

随机推荐