Vb.net
您好
我几个月来一直致力于一个项目(vb 2008 express)。最后一个问题 我无法解决。
我需要从'服务器'(监听器)向客户端发送图像。下面的代码大部分时间都有效,但有时图像不完整。我相信这可能与tcp数据包大小不同有关,可能受限于网络上的繁忙程度。一世 已经看到了将图像分成块并将它们发送出去的代码示例,但我无法让它们工作,因为我使用的是不同的vb版本。要发送的图片最小20k。
任何有效的代码示例都会很精彩。几个星期以来,我一直在试验和失败这个最后的障碍。
感谢您的期待。
客户端-----
Sub GetPic()
'------- Connect to Server
ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _ ProtocolType.Tcp)
ClientSocket.Connect(Epoint)
'------- Send Picture Request
Dim Bytes() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("Send Picture")
ClientSocket.Send(Bytes, Bytes.Length, SocketFlags.None)
'------- Receive Response
Dim RecvBuffer(20000) As Byte
Dim Numbytes As Integer
Numbytes = ClientSocket.Receive(RecvBuffer)
Dim Darray(Numbytes) As Byte
Buffer.BlockCopy(RecvBuffer, 0, Darray, 0, Numbytes)
'------- Close Connection
ClientSocket.Shutdown(SocketShutdown.Both)
ClientSocket.Close()
'-------
Dim MStrm = New MemoryStream(Darray)
Picture = Image.FromStream(MStrm)
End Sub
监听-----
'Threaded from a listener
Sub ClientThread(ByVal Client As TcpClient)
Dim MStrm As New MemoryStream
Dim Rbuffer(1024) As Byte
Dim Tbyte As Byte()
Dim NStrm As NetworkStream = Client.GetStream()
Dim I As Integer = NStrm.Read(Rbuffer, 0, Rbuffer.Length)
Dim Incoming As String = System.Text.Encoding.ASCII.GetString(Rbuffer, 0, I)
If Incoming = "Send Picture" then
Picture Save(MStrm, Picture.RawFormat)
Tbyte = MStrm.ToArray
NStrm.Write(Tbyte, 0, Tbyte.Length)
End if
Client.Close()
End Sub
答案 0 :(得分:1)
你获取图像的方式是错误的,这样做:
Numbytes = ClientSocket.Receive(RecvBuffer)
你很有可能获得部分数据,因为套接字实际上可以比它的缓冲区中的完整图像少一些。无论如何尝试接受它(我将在c#中给出样品):
MemoryStream responseStream = new MemoryStream();
byte[] recvBuffer = new recvBuffer[4096]; // just some size
int read = 0; // indicates how much data actually read from socket, can be smaller then buffer
do{
read = ClientSocket.Receive( recvBuffer ); // recieve data
responseStream.write( recvBuffer, 0, read ); // write it to resposne stream for later use
}
while( read != 0 );
这应该可行,但我会在你的情况下采取其他一些方式。这是客户的代码:
Socket s = new Socket( blablabla );
s.Connect( endPoint );
NetworkStream clientStream = new NetworkStream(s);
clientStream.Write( "Send picture" ); // send a command to server
int pictureSize = clientStream.ReadInt(); // here we expect to read following picture's size
byte[] pictureBuffer = clientStream.ReadBytes( pictureSize );
服务器,监听器部分:
Socket serverSocket = new Socket( blablabla );
serverSocket.Bind( blabla );
serverSocket.Listen( 100 );
while( true ){
Socket clientSocket = serverSocket.Accept();
Thread t = new Thread( new ParametrizedThreadStart( (object Obj) =>
{
Socket clientSocket = (Socket)Obj;
NetworkStream clientStream = new NetworkStream( clientSocket );
string command = clientStream.ReadString();
if( command == "Send picture" ){
// get ur picture here
// get it's size
clientStream.Write( pictureSize );
clientStream.Write( pictureBytes );
}
} ) );
t.start( clientSocket );
}
我希望这段伪代码清晰,随意提问:)