C#实现简易多人聊天室

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

只有一个群聊的功能

服务端

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.Threading.Tasks;
using System.Windows.Forms;

namespace FinalChatRoomClient
{
    public partial class Client : Form
    {
        //客户端负责接收服务端发来的数据消息的线程
        Thread threadClient = null;
        //创建客户端套接字,负责连接服务器
        Socket socketClient = null;

        public Client()
        {
            InitializeComponent();
            //关闭对文本框跨线程操作的检查
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }

        private void start_Click(object sender, EventArgs e)
        {
            //获得文本框中的IP地址对象
            IPAddress address = IPAddress.Parse(txtIp.Text.Trim());
            //创建包含IP和端口的网络节点对象
            IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
            //创建客户端套接字,负责连接服务器
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //客户端连接到服务器
                socketClient.Connect(endPoint);
                ShowMsg("客户端连接服务器成功");
            }
            catch (SocketException ex)
            {
                ShowMsg("客户端连接服务器发生异常:" + ex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg("客户端连接服务器发生异常:" + ex.Message);
            }

            threadClient = new Thread(ReceiveMsg);
            threadClient.IsBackground = true;
            threadClient.Start();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string strMsg = txtMsg.Text.Trim();
            //将字符串转成方便网络传送的二进制数组
            byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);
            byte[] arrMsgSend = new byte[arrMsg.Length + 1];
            arrMsgSend[0] = 0;//设置标识位,0代表发送的是文字
            Buffer.BlockCopy(arrMsg, 0, arrMsgSend, 1, arrMsg.Length);
            try
            {
                socketClient.Send(arrMsgSend);

                //清空发送消息文本框中的消息
                this.txtMsg.Text = "";
            }
            catch (SocketException ex)
            {
                ShowMsg("客户端发送消息时发生异常:" + ex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg("客户端发送消息时发生异常:" + ex.Message);
            }
        }

        private void ShowMsg(string msg)
        {
            txtRecord.AppendText(msg + "\r\n");
        }

        private void ReceiveMsg()
        {
            while (true)
            {
                //定义一个接收消息用的字节数组缓冲区(2M大小)
                byte[] arrMsgRev = new byte[1024 * 1024 * 2];
                //将接收到的数据存入arrMsgRev,并返回真正接收到数据的长度
                int length = -1;
                try
                {
                    length = socketClient.Receive(arrMsgRev);
                }
                catch (SocketException ex)
                {
                    ShowMsg("客户端接收消息时发生异常:" + ex.Message);
                    break;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("客户端接收消息时发生异常:" + ex.Message);
                    break;
                }

                //此时是将数组的所有元素(每个字节)都转成字符串,而真正接收到只有服务端发来的几个字符
                string strMsgReceive = Encoding.UTF8.GetString(arrMsgRev, 0, length);
                Console.WriteLine(strMsgReceive);
                ShowMsg(strMsgReceive);
            }
        }
    }
}

客户端

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.Threading.Tasks;
using System.Windows.Forms;

namespace FinalChatRoomClient
{
    public partial class Client : Form
    {
        //客户端负责接收服务端发来的数据消息的线程
        Thread threadClient = null;
        //创建客户端套接字,负责连接服务器
        Socket socketClient = null;

        public Client()
        {
            InitializeComponent();
            //关闭对文本框跨线程操作的检查
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }

        private void start_Click(object sender, EventArgs e)
        {
            //获得文本框中的IP地址对象
            IPAddress address = IPAddress.Parse(txtIp.Text.Trim());
            //创建包含IP和端口的网络节点对象
            IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
            //创建客户端套接字,负责连接服务器
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //客户端连接到服务器
                socketClient.Connect(endPoint);
                ShowMsg("客户端连接服务器成功");
            }
            catch (SocketException ex)
            {
                ShowMsg("客户端连接服务器发生异常:" + ex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg("客户端连接服务器发生异常:" + ex.Message);
            }

            threadClient = new Thread(ReceiveMsg);
            threadClient.IsBackground = true;
            threadClient.Start();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string strMsg = txtMsg.Text.Trim();
            //将字符串转成方便网络传送的二进制数组
            byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);
            byte[] arrMsgSend = new byte[arrMsg.Length + 1];
            arrMsgSend[0] = 0;//设置标识位,0代表发送的是文字
            Buffer.BlockCopy(arrMsg, 0, arrMsgSend, 1, arrMsg.Length);
            try
            {
                socketClient.Send(arrMsgSend);

                //清空发送消息文本框中的消息
                this.txtMsg.Text = "";
            }
            catch (SocketException ex)
            {
                ShowMsg("客户端发送消息时发生异常:" + ex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg("客户端发送消息时发生异常:" + ex.Message);
            }
        }

        private void ShowMsg(string msg)
        {
            txtRecord.AppendText(msg + "\r\n");
        }

        private void ReceiveMsg()
        {
            while (true)
            {
                //定义一个接收消息用的字节数组缓冲区(2M大小)
                byte[] arrMsgRev = new byte[1024 * 1024 * 2];
                //将接收到的数据存入arrMsgRev,并返回真正接收到数据的长度
                int length = -1;
                try
                {
                    length = socketClient.Receive(arrMsgRev);
                }
                catch (SocketException ex)
                {
                    ShowMsg("客户端接收消息时发生异常:" + ex.Message);
                    break;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("客户端接收消息时发生异常:" + ex.Message);
                    break;
                }

                //此时是将数组的所有元素(每个字节)都转成字符串,而真正接收到只有服务端发来的几个字符
                string strMsgReceive = Encoding.UTF8.GetString(arrMsgRev, 0, length);
                Console.WriteLine(strMsgReceive);
                ShowMsg(strMsgReceive);
            }
        }
    }
}

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

(0)

相关推荐

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

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

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

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

  • C#实现简单的聊天窗体

    本文实例为大家分享了C#实现简单的聊天窗体的具体代码,供大家参考,具体内容如下 一.要使用(学习)到的知识点 1.textBox控件 (1)功能:允许用户输入文本,并提供多行编辑和密码字符掩码功能 (2)它右什么属性? ​ ①Multiline ​ 表示获取或设置一个值,该值指示这是否为多行textBox控件 textBox2.Multiline = true;//意思就是将textbox2设置为可以多行显示 ​ ②TabIndex ​ 表示获取或设置控件在其容器内的Tab键顺序 textBox

  • c#多线程网络聊天程序代码分享(服务器端和客户端)

    XuLIeHua类库 复制代码 代码如下: using System;using System.Collections;  using System.Collections.Generic;using System.Threading;  using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.IO;using Sy

  • 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#基于WinForm的Socket实现简单的聊天室 IM

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

  • C#实现简单聊天程序的方法

    本文实例讲述了C#简单聊天程序实现方法.分享给大家供大家参考.具体如下: 假如有服务器端程序,ChatServer和客户端程序ChatClient.实现客户端向服务器端发送信息的简单功能. 运行步骤, 1.先是服务器端start listen, 2.然后客户端connect. 3.客户端发送消息   只要服务器端start listen了,然后客户端也connect了.这样建立起连接后.接受发送信息就方便了,只要用writer,reader去操作NetworkStream   服务器ChatSe

  • 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

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

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

  • C#聊天程序服务端与客户端完整实例代码

    本文所述为基于C#实现的多人聊天程序服务端与客户端完整代码.本实例省略了结构定义部分,服务端主要是逻辑处理部分代码,因此使用时需要完善一些窗体按钮之类的. 先看服务端代码如下: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using

随机推荐