none
如何应用Silverlight2的socket? RRS feed

  • 问题

  •  

    Server:

    Code Snippet

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;

    class MyTcpListener
    {
        public static void Main()
        {
            TcpListener server = null;
            try
            {
                // Set the TcpListener on port 13000.
                Int32 port = 4522;
                IPAddress localAddr = IPAddress.Parse("192.168.0.2");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine("Sent: {0}", data);
                    }

                    // Shutdown and end connection
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }


            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
    }

     

    Server-crossdomain.xml:

    Code Snippet

    <cross-domain-policy>
        <allow-access-from domain="*"/>
    </cross-domain-policy>

     

     

    Client:


    Code Snippet
                SocketClient sc = new SocketClient("192.168.0.2", 4522);
                sc.Connect();
                string z = sc.SendReceive("test");
                this.ScTxt.Text = z;

     

    Client-NetWork namespace:

    Code Snippet

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;

    namespace System.Prolight.SilverSocket
    {
        internal sealed class SocketClient : IDisposable
        {
            private const int Receive = 1;
            private const int Send = 0;

            private bool isConnected = false;

            private Socket socket;
            private DnsEndPoint endPoint;
            private IPEndPoint z;

            private static AutoResetEvent autoEvent = new AutoResetEvent(false);
            private static AutoResetEvent[] autoSendReceiveEvents = new AutoResetEvent[]
                    {
                            new AutoResetEvent(false),
                            new AutoResetEvent(false)
                    };

            internal SocketClient(string host, int port)
            {
                z = new IPEndPoint(IPAddress.Parse(host), port);
                endPoint = new DnsEndPoint(host, port);
                socket = new Socket(AddressFamily.InterNetwork
                    /* hostEndPoint.AddressFamily */,
                            SocketType.Stream, ProtocolType.Tcp);
            }

            internal void Connect()
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();

                args.UserToken = socket;
                args.RemoteEndPoint = z;
                args.Completed += new EventHandler(OnConnect);

                socket.ConnectAsync(args);
                autoEvent.WaitOne();

                if (args.SocketError != SocketError.Success)
                    throw new SocketException((int)args.SocketError);
            }

            internal void Disconnect()
            {
                socket.Close();
            }

            #region Events

            private void OnConnect(object sender, SocketAsyncEventArgs e)
            {
                autoEvent.Set();
                isConnected = (e.SocketError == SocketError.Success);
            }

            private void OnReceive(object sender, SocketAsyncEventArgs e)
            {
                autoSendReceiveEvents[Send].Set();
            }

            private void OnSend(object sender, SocketAsyncEventArgs e)
            {
                autoSendReceiveEvents[Receive].Set();

                if (e.SocketError == SocketError.Success)
                {
                    if (e.LastOperation == SocketAsyncOperation.Send)
                    {
                        // Prepare receiving.
                        Socket s = e.UserToken as Socket;

                        byte[] response = new byte[255];
                        e.SetBuffer(response, 0, response.Length);
                        e.Completed += new EventHandler(OnReceive);
                        s.ReceiveAsync(e);
                    }
                }
                else
                {
                    ProcessError(e);
                }
            }

            #endregion

            private void ProcessError(SocketAsyncEventArgs e)
            {
                Socket s = e.UserToken as Socket;
                if (s.Connected)
                {
                    try
                    {
                        s.Shutdown(SocketShutdown.Both);
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        if (s.Connected)
                            s.Close();
                    }
                }

                throw new SocketException((int)e.SocketError);
            }

            internal String SendReceive(string message)
            {
                if (isConnected)
                {
                    Byte[] bytes = Encoding.UTF8.GetBytes(message);

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.SetBuffer(bytes, 0, bytes.Length);
                    args.UserToken = socket;
                    args.RemoteEndPoint = endPoint;
                    args.Completed += new EventHandler(OnSend);

                    socket.SendAsync(args);

                    AutoResetEvent.WaitAll(autoSendReceiveEvents);

                    return Encoding.UTF8.GetString(args.Buffer, args.Offset, args.BytesTransferred);
                }
                else
                    throw new SocketException((int)SocketError.NotConnected);
            }

            #region IDisposable Members

            public void Dispose()
            {
                autoEvent.Close();
                autoSendReceiveEvents[Send].Close();
                autoSendReceiveEvents[Receive].Close();
                if (socket.Connected)
                    socket.Close();
            }

            #endregion
        }
    }

     

     

    查了好多资料,写了一个Server 跟 Silverlight2的Client,可是就是两边连接不上啊,郁闷,请达人指点迷津

    那个Server端口只有4502-4532这个我也设了,还有看有的说xap要在80端口下,我把测试的webapplication也设置到80端口下了,都不行> <~ ,还有还是有时候出现莫名不能调试的问题

    2008年5月2日 2:30
    版主

答案

  •  

    晕死,还是安全性问题,slight2太安全点了吧,ip地址改用127.0.0.1调试成功....折腾了我那是三天三夜呀.各位达人,我要用指定的ip有没有办法呀 192.168.0.2,看资料好像 xap那个文件目前好像必须要跟Server放在一个服务器上才可以Socket...否则一律xx,
    2008年5月3日 14:59
    版主

全部回复

  •  

    晕死,还是安全性问题,slight2太安全点了吧,ip地址改用127.0.0.1调试成功....折腾了我那是三天三夜呀.各位达人,我要用指定的ip有没有办法呀 192.168.0.2,看资料好像 xap那个文件目前好像必须要跟Server放在一个服务器上才可以Socket...否则一律xx,
    2008年5月3日 14:59
    版主
  •  

    可以用一个什么policy的东西放在服务器上运行,这样就可以直接访问了。
    2008年7月1日 1:02
  •  

    Beta2的Socket安全方式改了,比Beta1方便一些啦
    2008年7月1日 1:30
    版主