我通过socket传binary文件,发送端读取文件并通过数据流发送给对端。对端接收时需要先申请一个字节数组,例如:
dim buffer(1024)as byte,但发送的数据没有1024这么大,例如发送了200字节,会导致1024中申请的内存过大,剩下的800多空间是没有用的,如何能够清除掉?vb.net在发送时不能标记结尾吗?
trim这类方法都试过了,行不通。求高人解决。

解决方案 »

  1.   

    http://www.codeproject.com/KB/IP/ChatAsynchTCPSockets.aspx上的例子。Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                             ProtocolType.Tcp);
    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
    sock.Bind (iep);
    sock.Listen (5);
    sock.BeginAccept (new AsyncCallback(CallAccept), sock);private void CallAccept(IAsyncResult iar)
    {
        Socket server = (Socket)iar.AsyncState;
        Socket client = server.EndAccept(iar);
    }class Data
    {
        //Default constructor
        public Data()
        {
            this.cmdCommand = Command.Null;
            this.strMessage = null;
            this.strName = null;
        }    //Converts the bytes into an object of type Data
        public Data(byte[] data)
        {
            //The first four bytes are for the Command
            this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);        //The next four store the length of the name
            int nameLen = BitConverter.ToInt32(data, 4);        //The next four store the length of the message
            int msgLen = BitConverter.ToInt32(data, 8);        //Makes sure that strName has been passed in the array of bytes
            if (nameLen > 0)
                this.strName = Encoding.UTF8.GetString(data, 12, nameLen);
            else
                this.strName = null;        //This checks for a null message field
            if (msgLen > 0)
                this.strMessage = Encoding.UTF8.GetString(data, 
                                  12 + nameLen, msgLen);
            else
                this.strMessage = null;
        }    //Converts the Data structure into an array of bytes
        public byte[] ToByte()
        {
            List<byte> result = new List<byte>();        //First four are for the Command
            result.AddRange(BitConverter.GetBytes((int)cmdCommand));        //Add the length of the name
            if (strName != null)
                result.AddRange(BitConverter.GetBytes(strName.Length));
            else
                result.AddRange(BitConverter.GetBytes(0));        //Length of the message
            if (strMessage != null)
                result.AddRange(BitConverter.GetBytes(strMessage.Length));
            else
                result.AddRange(BitConverter.GetBytes(0));        //Add the name
            if (strName != null)
                result.AddRange(Encoding.UTF8.GetBytes(strName));        //And, lastly we add the message text to our array of bytes
            if (strMessage != null)
                result.AddRange(Encoding.UTF8.GetBytes(strMessage));        return result.ToArray();
        }    //Name by which the client logs into the room
        public string strName;
        //Message text
        public string strMessage;
        //Command type (login, logout, send message, etc)
        public Command cmdCommand;
    }TCP Server
    //The ClientInfo structure holds 
    //the required information about every
    //client connected to the server
    struct ClientInfo
    {
        //Socket of the client
        public Socket socket;
        //Name by which the user logged into the chat room
        public string strName;
    }//The collection of all clients logged 
    //into the room (an array of type ClientInfo)
    ArrayList clientList;//The main socket on which the server listens to the clients
    Socket serverSocket;byte[] byteData = new byte[1024];Here is how it starts listening for the clients and accepts the incoming requests:private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            //We are using TCP sockets
            serverSocket = new Socket(AddressFamily.InterNetwork, 
                                      SocketType.Stream, 
                                      ProtocolType.Tcp);
            
            //Assign the any IP of the machine and listen on port number 1000
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);        //Bind and listen on the given address
            serverSocket.Bind(ipEndPoint);
            serverSocket.Listen(4);        //Accept the incoming clients
            serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
        }
        catch (Exception ex)
        { 
            MessageBox.Show(ex.Message, "SGSserverTCP", 
                MessageBoxButtons.OK, MessageBoxIcon.Error); 
        }
    }Below is the corresponding OnAccept function:private void OnAccept(IAsyncResult ar)
    {
        try
        {
            Socket clientSocket = serverSocket.EndAccept(ar);        //Start listening for more clients
            serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);        //Once the client connects then start 
            //receiving the commands from her
            clientSocket.BeginReceive(byteData, 0, 
                byteData.Length, SocketFlags.None, 
                new AsyncCallback(OnReceive), clientSocket);
        }
        catch (Exception ex)
        { 
            MessageBox.Show(ex.Message, "SGSserverTCP", 
                MessageBoxButtons.OK, MessageBoxIcon.Error); 
        }
    }
    TCP Client//The main client socket
    public Socket clientSocket;
    //Name by which the user logs into the room
    public string strName;private byte[] byteData = new byte[1024];The client firstly connects to the server:try
    {
        //We are using TCP sockets
        clientSocket = new Socket(AddressFamily.InterNetwork,
                       SocketType.Stream, ProtocolType.Tcp);    IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
        //Server is listening on port 1000
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);    //Connect to the server
        clientSocket.BeginConnect(ipEndPoint, 
            new AsyncCallback(OnConnect), null);
    }
    catch (Exception ex)

        MessageBox.Show(ex.Message, "SGSclient", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Error); 
    }
    //Broadcast the message typed by the user to everyone
    private void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            //Fill the info for the message to be send
            Data msgToSend = new Data();
            
            msgToSend.strName = strName;
            msgToSend.strMessage = txtMessage.Text;
            msgToSend.cmdCommand = Command.Message;        byteData = msgToSend.ToByte();        //Send it to the server
            clientSocket.BeginSend (byteData, 0, byteData.Length, 
                SocketFlags.None, 
                new AsyncCallback(OnSend), null);        txtMessage.Text = null;
        }
        catch (Exception)
        {
            MessageBox.Show("Unable to send message to the server.", 
                            "SGSclientTCP: " + strName, 
                            MessageBoxButtons.OK, 
                            MessageBoxIcon.Error);
        }  
    }