从服务器向所有客户端发送数据[聊天] [英] Send data To All Client From Server [Chat]

查看:71
本文介绍了从服务器向所有客户端发送数据[聊天]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

我做了一个聊天系统应用程序

客户端可以向服务器发送数据,服务器可以从所有客户端接收数据.

但我有一个问题:

我希望服务器可以将数据发送到所有客户端

例如:

如果客户端A向服务器发送数据,则服务器接收数据并发送给其他客户端(B C D ...)

这是完整的代码(服务器端):

hello

i made a Chat System App

Clients Can Send data to Server, and Server can Receive Data From all Client.

but i have a problem in it:

i want that Server can Send Data to all Client,

for Example:

if Client A send Data to Server, server receive data and send to other Client ( B C D ... )

this is a full code ( side Server ):

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

namespace chat_Server
{
    public partial class Form1 : Form
    {
        Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ServerIP = new IPEndPoint(IPAddress.Any, 6634);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ServerSocket.Bind(ServerIP);
            ServerSocket.Listen(10);
            Thread StartT = new Thread(Start);
            StartT.Start();
            MessageBox.Show("Server Started...");
        }

        void Start()
        {
            while (true)
            {
                ConnectionThread newconnection = new ConnectionThread();
                try
                {
                    newconnection.client = ServerSocket.Accept();
                }

                catch
                {
                    break;
                }

                Thread newThread = new Thread(new ThreadStart(newconnection.HandleConnection));
                newThread.Start();
            }
        }
        class ConnectionThread
        {
            private static Dictionary<int, Socket> allSocket = new Dictionary<int, Socket>();
            string Spliter = "~$%^&";
            string ReverseSpliter = "&^%$~";
            public Socket client;
            int BufferSize = 100000;
            private static int rand = 0;
            int id = 0;
            
            public void HandleConnection()
            {

                int recv;
                byte[] data = new byte[BufferSize];
                string textRecieve;
                string StringData;
                rand++;
                id = rand;
                allSocket.Add(rand, client);
                recv = client.Receive(data);
                textRecieve = Encoding.Unicode.GetString(data, 0, recv);

                string[] txtR = GetDataPart(textRecieve);

                if (txtR[0] == "hi")
                {
                    MessageBox.Show("Show Hi");
                }
                else if (txtR[0] == "bye")
                {
                    MessageBox.Show("Show Bye");
                }

                    try
                    {
                        while (true)
                        {
                            data = new byte[BufferSize];
                            recv = client.Receive(data);
                            if (recv == 0)
                            {
                                allSocket.Remove(id);
                                client.Close();
                                break;                                
                            }
                            StringData = Encoding.Unicode.GetString(data, 0, recv);
                            txtR = GetDataPart(StringData);

                            if (txtR[0] == "Send")
                            {
                                MessageBox.Show("Client type --> Send");
                            }
                            else
                                SendText(StringData);
                            
                        }
                    }
                    catch
                    {
                        allSocket.Remove(id);
                    }
            }
            void SendText(string Data)
            {
                string[] txtR = GetDataPart(Data);
                for (int i = 0; i < id; i++)
                {

                    allSocket[id].Send(Encoding.Unicode.GetBytes(Data));
                } 
            }

            string[] GetDataPart(string StringData)
            {
                string[] txtR = new string[10];
                int Index = 0;
                int LastIndex = 0;
                int j = 0;
                for (int i = 0; i < 10; i++)
                    txtR[i] = "";
                while (Index != -1)
                {
                    Index = StringData.IndexOf(Spliter, LastIndex);
                    if (Index != -1)
                    {
                        if ((Index + 5) == StringData.Length || ((Index + 10) < StringData.Length || StringData.Substring(Index + 5, 5) != ReverseSpliter))
                        {
                            txtR[j] += StringData.Substring(LastIndex, Index - LastIndex);
                            j++;
                            LastIndex = Index + 5;
                        }
                        else if ((Index + 10) < StringData.Length && StringData.Substring(Index + 5, 5) == ReverseSpliter)
                        {
                            txtR[j] += StringData.Substring(LastIndex, Index - LastIndex + 5);
                            LastIndex = Index + 10;
                        }
                    }
                }
                return txtR;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            ServerSocket.Close();
            Application.Exit();
            Application.ExitThread();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            ServerSocket.Close();
        }
    }
}




我如何向所有客户端发送数据? (例如聊天室)




how can i send data to all client ? (Like Chat Room)

推荐答案

%^&"; 字符串 ReverseSpliter = "
%^&"; string ReverseSpliter = "&^%


〜"; public 套接字客户端; int BufferSize = 100000 ; 私有 静态 int rand = 0 ; int id = 0 ; 公共 无效 HandleConnection() { int recv; 字节 []数据= 字节 [缓冲区大小]; 字符串 textRecieve; 字符串 StringData; rand ++; id = rand; allSocket.Add(rand,client); recv = client.Receive(数据); textRecieve = Encoding.Unicode.GetString(data, 0 ,recv); 字符串 [] txtR = GetDataPart(textRecieve); 如果(txtR [ 0 ] == " 嗨") { MessageBox.Show(" ); } 其他 如果(txtR [ 0 ] = = " ) { MessageBox.Show(" ); } 尝试 { 同时() { 数据= 字节 [BufferSize]; recv = client.Receive(数据); 如果(recv == 0 ) { allSocket.Remove(id); client.Close(); break ; } StringData = Encoding.Unicode.GetString(data, 0 ,recv); txtR = GetDataPart(StringData); 如果(txtR [ 0 ] == " 发送") { MessageBox.Show(" ); } 其他 SendText(StringData); } } 捕获 { allSocket.Remove(id); } } 无效 SendText(字符串数据) { 字符串 [] txtR = GetDataPart(Data); for ( int i = 0 ; i < id; i ++) { allSocket [id] .Send(Encoding.Unicode.GetBytes(Data)); } } 字符串 [] GetDataPart(字符串 StringData) { 字符串 [] txtR = 字符串 [ 10 ]; int 索引= 0 ; int LastIndex = 0 ; int j = 0 ; for ( int i = 0 ; i < 10 ; i ++) txtR [i] = " ; while (索引!= -1) { 索引= StringData.IndexOf(Spliter,LastIndex); 如果(索引!= -1) { 如果(((Index + 5 )== StringData.Length ||((Index + 10 )< StringData.Length || StringData.Substring(Index + 5 5 != ReverseSpliter)) { txtR [j] + = StringData.Substring(LastIndex,Index-LastIndex); j ++; LastIndex =索引+ 5 ; } 其他 如果((索引+ 10 ) < StringData.Length&& StringData.Substring(Index + 5 5 ); LastIndex =索引+ 10 ; } } } 返回 txtR; } } 私有 无效 Form1_FormClosing(对象发​​件人,FormClosingEventArgs e) { ServerSocket.Close(); Application.Exit(); Application.ExitThread(); } 私有 无效 btnStop_Click(对象发​​件人,EventArgs e) { ServerSocket.Close(); } } }
~"; public Socket client; int BufferSize = 100000; private static int rand = 0; int id = 0; public void HandleConnection() { int recv; byte[] data = new byte[BufferSize]; string textRecieve; string StringData; rand++; id = rand; allSocket.Add(rand, client); recv = client.Receive(data); textRecieve = Encoding.Unicode.GetString(data, 0, recv); string[] txtR = GetDataPart(textRecieve); if (txtR[0] == "hi") { MessageBox.Show("Show Hi"); } else if (txtR[0] == "bye") { MessageBox.Show("Show Bye"); } try { while (true) { data = new byte[BufferSize]; recv = client.Receive(data); if (recv == 0) { allSocket.Remove(id); client.Close(); break; } StringData = Encoding.Unicode.GetString(data, 0, recv); txtR = GetDataPart(StringData); if (txtR[0] == "Send") { MessageBox.Show("Client type --> Send"); } else SendText(StringData); } } catch { allSocket.Remove(id); } } void SendText(string Data) { string[] txtR = GetDataPart(Data); for (int i = 0; i < id; i++) { allSocket[id].Send(Encoding.Unicode.GetBytes(Data)); } } string[] GetDataPart(string StringData) { string[] txtR = new string[10]; int Index = 0; int LastIndex = 0; int j = 0; for (int i = 0; i < 10; i++) txtR[i] = ""; while (Index != -1) { Index = StringData.IndexOf(Spliter, LastIndex); if (Index != -1) { if ((Index + 5) == StringData.Length || ((Index + 10) < StringData.Length || StringData.Substring(Index + 5, 5) != ReverseSpliter)) { txtR[j] += StringData.Substring(LastIndex, Index - LastIndex); j++; LastIndex = Index + 5; } else if ((Index + 10) < StringData.Length && StringData.Substring(Index + 5, 5) == ReverseSpliter) { txtR[j] += StringData.Substring(LastIndex, Index - LastIndex + 5); LastIndex = Index + 10; } } } return txtR; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { ServerSocket.Close(); Application.Exit(); Application.ExitThread(); } private void btnStop_Click(object sender, EventArgs e) { ServerSocket.Close(); } } }




我如何向所有客户端发送数据? (如聊天室)




how can i send data to all client ? (Like Chat Room)


最好的选择是,您可以将ServerSocket添加到客户端.

在这种情况下,您需要在激活套接字后将详细信息发送到客户端.将客户端套接字详细信息提供给服务器.在服务器数据库中.每当服务器要连接客户端时.然后,它可以通过客户端的服务器套接字将这些详细信息发送到客户端计算机.这样,您就可以与双方交流.
The best option, you can add a ServerSocket to client.

In this you need to send details after activating socket to client. Give client socket details to server. In server database. Whenever server wants to connect client. Then it can send these details to client machine via client''s server socket. In this way you can interact with both side communication.


这篇关于从服务器向所有客户端发送数据[聊天]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆