C# socket 传输对象

 socket传输对象可以是用序列化和反序列化, 

clinet:
把对象变用BinaryFormatter对象的Serialize()序列化MemoryStream 类的stream 
然后用stream.ToArray()变为byte[],
然后通过socket传过去

server:
接收byte[],
然后用BinaryWriter类,写入stream
然后为了避免 //在分析完成之前就遇到流结尾
stream.Position = 0; //需要把流指针放到0位,
然后用BinaryFormatter对象的Deserialize()反序列化,
然后强制转化成原来的对象类型

note: client 和server所传输的对象的类, 需要放在一个公共的dll里面,

code:
//server
    static void Main(string[] args)
        {

            int port = 8080;
            int backlog = 100;
            Socket listenSocket new Socket(AddressFamily .InterNetwork,
                                   SocketType.Stream ,
                                   ProtocolType.Tcp );

            IPAddress hostIP IPAddress .Parse("127.0.0.1" );
            IPEndPoint ep new IPEndPoint(hostIP, port );
            listenSocket.Bind (ep);

            // start listening
            Console.WriteLine ("waitting..");
            listenSocket.Listen (backlog);

            Socket serverSocket listenSocket .Accept();
            Console.WriteLine ("accept..");

   //主要代码
            byte[] buf null ;
            string str "" ;
            int bytes = 0;
            Stream stream new MemoryStream();
            BinaryWriter bw new BinaryWriter(stream);
            IFormatter form new BinaryFormatter();
            data d null ;

            if (serverSocket .Connected)
            {
                do
                {
                    buf = new byte [1024 ];
                    bytes = serverSocket.Receive (buf);
                    bw.Write (buf);
                    //在分析完成之前就遇到流结尾
                    stream.Position = 0; //需要把流指针放到0位
                    d = (data)form.Deserialize( stream);
                    d.print ();                 
                } while (bytes > 0 );
             
                serverSocket.Send(Encoding.Unicode. GetBytes("finish" ));
                serverSocket.Close();
            }
            else{
                Console.WriteLine("error");
            }
            Console.WriteLine("ending");
        }
    }

//client
  Byte[] bytesSent null ;
        Byte[] bytesReceived new Byte[256];
       Socket s ConnectSocket(server, port);//这个函数得自己写啊, 我就不放出来了,反正就是返回一个连好的套接字

        if (s == null )
            return ("Connection failed" );

        //主要代码
        data d new data();
        MemoryStream stream new MemoryStream();
        IFormatter form new BinaryFormatter();
        form.Serialize (stream, d);

        bytesSent = stream.ToArray ();
        s.Send (bytesSent);
        s.Shutdown (SocketShutdown. Send);
        s.Close();


没有更多推荐了,返回首页