我尝试序列化MessageData类并通过网络发送它。 这个类包含我需要在表单上显示的位图图片。 传输的位图是网络摄像头需要通过网络每秒多次传输到WinForm的帧。 这个程序是一个测试,将来将分为两部分,一部分是接收方法和winform的客户端部分,另一部分是网络摄像头和发送方法。
实际上对象图片的序列化和发送 - 接收不起作用,如果我强制图片从序列化网络进程实例直接获取它,则winform不显示任何图像。 网络摄像头帧是使用Emgu.CV库管理的,并且在本地它可以正常工作,但不能远程通过帧的序列化发送。 以下所有内容都在命名空间Idea中:
[Serializable]
public class MessageData {
public MessageData(Bitmap img){
Picture = img;
}
public static Bitmap Picture { get; set; }
}
[Serializable]
public class MessageSendData {
public MessageSendData(Bitmap img){
Picture = img;
}
public static Bitmap Picture { get; set; }
}
public partial class Idea : Form
{
//declaring global variables
private Capture capture; //takes images from camera as image frames
private bool captureInProgress; // checks if capture is executing
private TcpListener ascolto;
Bitmap bitmapricevuto;
public Idea()
{
InitializeComponent();
}
private void Idea_Load(object sender, EventArgs e)
{
}
private void ProcessFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> ImageFrame = capture.QueryFrame(); //line 1
// CamImageBox.Image = byteArrayToImage(MyImageBytes(ImageFrame.ToBitmap()));
// CamImageBox.Image = ImageFrame.ToBitmap();
Thread r = new Thread(Ricevi);
r.Start();
MessageSendData.Picture = ImageFrame.ToBitmap();
Thread s = new Thread(Spedisci);
s.Start();
lock (MessageData.Picture){
CamImageBox.Image = MessageData.Picture;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
#region if capture is not created, create it now
if (capture == null)
{
try
{
capture = new Capture();
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
#endregion
if (capture != null)
{
if (captureInProgress)
{ //if camera is getting frames then stop the capture and set button Text
// "Start" for resuming capture
btnStart.Text = "Start!"; //
Application.Idle -= ProcessFrame;
}
else
{
//if camera is NOT getting frames then start the capture and set button
// Text to "Stop" for pausing capture
btnStart.Text = "Stop";
Application.Idle += ProcessFrame;
}
captureInProgress = !captureInProgress;
}
}
private void ReleaseData()
{
if (capture != null)
capture.Dispose();
}
public static void Ricevi()
{
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(address, 8585);
listener.Start();
Bitmap mia;
try
{
using (TcpClient client = listener.AcceptTcpClient())
{
NetworkStream stream = client.GetStream();
IFormatter formatter = new BinaryFormatter();
while (true)
{
lock (MessageData.Picture){
MessageData.Picture = (Bitmap)formatter.Deserialize(stream);
}
}
}
}
catch(Exception ex) { }
return;
}
public static void Spedisci()
{
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpClient client = new TcpClient();
try
{
client.Connect(address, 8585);
// Retrieve the network stream.
NetworkStream stream = client.GetStream();
IFormatter formatter = new BinaryFormatter();
while(true)
{
lock (MessageSendData.Picture) {
formatter.Serialize(stream, MessageSendData.Picture);
//Thread.Sleep(1000);
}
}
}
catch (Exception ex) { }
}
/*
public byte[] MyImageBytes(Image MyImage)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
}
public Image byteArrayToImage(byte[] bytesArr)
{
MemoryStream memstr = new MemoryStream(bytesArr);
Image img = Image.FromStream(memstr);
return img;
}
*/
}
} &#39;
我已经实现了两种方法:1-First方法转换字节数组中的位图。 2秒方法转换位图中的字节数组。直接测试它们而不通过tcp网络发送转换后的字节我看到所有软件都在工作。现在我创造了两种方法&#34; Invia&#34;和&#34; Ricevi&#34;通过异步方法发送和接收bytearrays,通过将它们分成1024个长度的流。关于编译异步任务方法返回类型的问题我的问题。如何修复此线程任务异步问题? &#39;
private void ProcessFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> ImageFrame = capture.QueryFrame();
invia(MyImageBytes(ImageFrame.ToBitmap()));
CamImageBox.Image = ricevi();
}
public byte[] MyImageBytes(Image MyImage)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
}
&#39;
发送(Invia)和接收(Ricevi)方法的最后一个版本如下所示,使用转换为字节数组的字符并附加到位图字节数组,用于发送和接收位图。实际上我在编译期间遇到了问题:
public static void invia(byte[] bytetosend)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
var mahByteArray = new ArrayList<byte>();
mahByteArray.AddRange(bytetosend);
string eof = "<EOF>";
mahByteArray.Insert(0, Convert.ToByte(eof)); // Adds eof bytes to the beginning.
byte[] msg = mahByteArray.ToArray();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static void ricevi()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
var scambioArray = new ArrayList();
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string eofr = "<EOF>";
byte[] trova = Convert.ToByte(eofr);
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
if (bytes.IndexOf(trova))
{
var mahByteArray = new ArrayList();
mahByteArray.AddRange(bytes);
mahByteArray.Remove(trova);
bytes = mahByteArray.ToArray();
break;
}
scambioArray.AddRange(bytes);
}
// Echo the data back to the client.
byte[] msg = scambioArray.ToArray();
MessageData.Picture = byteArrayToImage(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
答案 0 :(得分:0)
尝试这样的事情
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,500,100' rel='stylesheet' type='text/css'>
<link rel='stylesheet' href='style.css'/>
</head>
<body>
<div class="header">
<div class="container">
<h1> INNOVATION CLOUD </h1>
<p>CONNECT YOUR IDEAS GLOBALLY</p>
<input class="btn" type="button" value="Learn More">
</div>
</div>
<div class="nav">
<div class="container">
<ul>
<li>Register</li>
<li>Schedule</li>
<li>Sponsors</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
<div class="main">
<div class="container">
<img id="mainImage" src="https://s3.amazonaws.com/codecademy-content/projects/innovation-cloud/cloud.svg" />
<h2>The Innovation Cloud Conference</h2>
<p>Connect with the best minds across a wide range of industries to share ideas and brainstorm new solutions to challenging problems.</p>
<p>Hear industry leaders talk about what worked (and what didn't) so that you can save time on your most challenging projects.</p>
<p>Learn about the latest research and technologies that you can use immediately to invent the future.</p>
</div>
</div>
<div class="clreafix"></div>
<div class="jumbotron">
<div class="container">
</div>
</div>
</body>
</html>