如何将对象发送回所有客户端 [英] How to send object back out to all clients

查看:59
本文介绍了如何将对象发送回所有客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止的代码。它正在工作,可以接收对象。但是我想将我返回的对象发送给所有连接的客户端。我猜我需要某种类型的arraylist来存储连接的客户端。我该怎么做?



我目前的代码:

  class  TcpServer 
{
private TcpListener _server;
private Boolean _isRunning;

public TcpServer( int port)
{
_server = new TcpListener(IPAddress.Any,port);
_server.Start();

_isRunning = true ;

LoopClients();
}

public void LoopClients()
{
while (_ isRunning)
{
// 等待客户端连接
TcpClient newClient = _server.AcceptTcpClient();
// 找到客户。
// 创建一个处理通信的线程
线程t = 线程( new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}

public void HandleClient( object obj)
{
// 从传递给线程的参数中检索客户端
TcpClient client =(TcpClient)obj;
// 设置两个流
StreamWriter sWriter = new StreamWriter(client.GetStream(),Encoding.ASCII);
StreamReader sReader = new StreamReader(client.GetStream(),Encoding.ASCII);
// 您可以使用NetworkStream进行读写,
// 但即使请求也没有强制刷新
布尔 bClientConnected = true ;
Person p = null ;
while (bClientConnected)
{
try
{
// 从流中读取
// 如果我想要的话,我可以让对象回来
// 但我想将此对象发回给所有客户
// NetworkStream strm = client.GetStream();
// IFormatter formatter = new BinaryFormatter();
// p =(Person)formatter。反序列化(STRM); //你必须转换反序列化的对象
// strm.Close();
// 在控制台上显示内容。
// Console.WriteLine(新人物对象:名字>+ p.FirstName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}
}
}

解决方案

是的,您需要存储连接的客户端。例如,它可能是由于调用 System.IO.Sockets.TcpListener.AcceptTcpClient TcpClient 的实例$ c>或实例 Socket 因调用 System.IO.Sockets.TcpListener.AcceptSocket 而获得:

http://msdn.microsoft。 com / en-us / library / vstudio / system.net.sockets.tcplistener.accepttcpclient [ ^ ],

http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.acceptsocket [ ^ ]。


您可以在服务器端有两个独立的线程,一个接受新客户端,另一个发送/接收数据。您需要在访问此集合时使用线程同步。但是,永远不要使用 ArrayList 。早在.NET Framework v.2.0开发泛型时,此集合就已过时。它没有被正式标记为过时,只是因为它可以找到对遗留代码的支持,但对于新的开发它根本没有任何意义;它比普通集合更容易出错。使用 System.Collections.Generic 的集合。



如果这个答案与我以前的答案重复,很抱歉,将值从javascript传递给PHP(隐藏字段) [ ^ ]。

我只是添加一些细节。



现在,无论在哪里数据从客户端传输到服务器或服务器到客户端。通常,这是一个替代方向,如在对话框中:请求 - 响应,两者都可以携带一些信息,而不仅仅是确认。这是您的应用程序层协议的问题: http://en.wikipedia.org/wiki/ Application_layer [ ^ ]。



即使你不称它为协议,这种协议也总是存在于事实上,明示或暗示。



-SA

Here's the code I've got so far. It is working and can receive objects. However I want to send the object I get back out to all connected clients. I'm guessing I would need an arraylist of some sort to store the connected clients. How do I do this?

My current code:

class TcpServer
    {
        private TcpListener _server;
        private Boolean _isRunning;

        public TcpServer(int port)
        {
            _server = new TcpListener(IPAddress.Any, port);
            _server.Start();

            _isRunning = true;

            LoopClients();
        }

        public void LoopClients()
        {
            while (_isRunning)
            {
                // wait for client connection
                TcpClient newClient = _server.AcceptTcpClient();
                // client found.
                // create a thread to handle communication
                Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
                t.Start(newClient);
            }
        }

        public void HandleClient(object obj)
        {
            // retrieve client from parameter passed to thread
            TcpClient client = (TcpClient)obj;
            // sets two streams
            StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
            StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);
            // you could use the NetworkStream to read and write, 
            // but there is no forcing flush, even when requested
            Boolean bClientConnected = true;
            Person p = null;
            while (bClientConnected)
            {
                try
                {
                    // reads from stream
                    //Here if I wanted I could get the object back
                    //But I want to send this object back out to all clients
                    //NetworkStream strm = client.GetStream();
                    //IFormatter formatter = new BinaryFormatter();
                    //p = (Person)formatter.Deserialize(strm); // you have to cast the deserialized object
                    //strm.Close();
                    // shows content on the console.
                    //Console.WriteLine("New person object: First name > " + p.FirstName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
               
            }
        }
    }

解决方案

Yes, you need to store the connected clients. For example, it could be the instances of TcpClient obtained as a result of a call to System.IO.Sockets.TcpListener.AcceptTcpClient or instances Socket obtained as a result of a call to System.IO.Sockets.TcpListener.AcceptSocket:
http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.accepttcpclient[^],
http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.acceptsocket[^].

You could have two separate threads on the server side, one accepting new clients, another sending/receiving data. You will need to use thread synchronization at the access to this collection. However, never use ArrayList. This collection was rendered obsolete as early as of .NET Framework v.2.0, when generic were developed. It was not marked obsolete formally only because it would be find for support of legacy code, but for new development it makes no sense at all; it us more error-prone than generic collections. Use the collections of System.Collections.Generic.

Sorry if this answer is a duplicate on my previous answer, Passing value from javascript to PHP ( Hidden Field )[^].
I'm only adding some detail.

Now, it does not matter where the data is transmitted, from client to server or server to client. Usually, this is an alternative direction, like in a dialog: request-response, and both can carry some information, not only just the confirmation. This is a matter of your application-layer protocol: http://en.wikipedia.org/wiki/Application_layer[^].

Even if you don't call it "protocol", such protocol always exist de-facto, explicit or implied.

—SA


这篇关于如何将对象发送回所有客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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