C#使用Socket实现发送和接收图片的方法
本文实例讲述了C#使用Socket实现发送和接收图片的方法。分享给大家供大家参考。具体如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Net.Sockets; usingSystem.Net; usingSystem.IO; namespaceConsoleApplication1 { ClassProgram { staticvoidMain(String[]args) { //1.tocreateasocket SocketsListen=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //2.FillIP IPAddressIP=IPAddress.Parse("127.0.0.1"); IPEndPointIPE=newIPEndPoint(IP,4321); //3.binding sListen.Bind(IPE); //4.Monitor Console.WriteLine("Serviceislistening..."); sListen.Listen(2); //5.looptoacceptclientconnectionrequests while(true) { SocketclientSocket; try { clientSocket=sListen.Accept(); } catch { throw; } //senddatatotheclient //clientSocket.Send(Encoding.Unicode.GetBytes("Iamaserver,youthere??!!!!")); //sendthefile byte[]buffer=ReadImageFile("1.jpg"); clientSocket.Send(buffer,buffer.Length,SocketFlags.None); Console.WriteLine("Sendsuccess!"); } } privatestaticbyte[]ReadImageFile(Stringimg) { FileInfofileinfo=newFileInfo(img); byte[]buf=newbyte[fileInfo.Length]; FileStreamfs=newFileStream(img,FileMode.Open,FileAccess.Read); fs.Read(buf,0,buf.Length); fs.Close(); //fileInfo.Delete(); GC.ReRegisterForFinalize(fileinfo); GC.ReRegisterForFinalize(fs); returnbuf; } } }
客户端接收和保存图片的代码如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Net.Sockets; usingSystem.Net; usingSystem.IO; namespaceConsoleApplication2 { ClassProgram { staticvoidMain(String[]args) { //1.tocreateasocket SocketS=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //2.fillintheremoteIP IPAddressIP=IPAddress.Parse("127.0.0.1"); IPEndPointIPE=newIPEndPoint(IP,4321); Console.WriteLine("startedconnectionservice...."); //3.connecttotheserver s.Connect(IPE); //4.receivedata byte[]buffer=newbyte[1000000]; s.Receive(buffer,buffer.Length,SocketFlags.None); //varMsg=Encoding.Unicode.GetString(buffer); //Console.WriteLine("receivedmessage:(0)",msg); Console.WriteLine("Receivesuccess"); FileStreamfs=File.Create("1.jpg"); fs.Write(buffer,0,buffer.Length); fs.Close(); Console.ReadKey(); } } }
希望本文所述对大家的C#程序设计有所帮助。