发送/ C#中接收图像通过TCP套接字 [英] Sending/Receiving Image over TCP Socket in C#

查看:113
本文介绍了发送/ C#中接收图像通过TCP套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将图像发送到连接到我的TCP听者(服务器)客户。我成功地发送和接收文本通过网络,但是我无法从我的服务器发送图片给客户端。我想Dislpay放置在客户端窗口中图片框的图片。
下面是我使用的发送和接收文本的但不能想象一个代码

I am trying to Send the image to the Client which is connected to my TCP Listner (Server). I am successfully sending and receiving text over Network but I am unable to send the picture to the client from my server. I want to Dislpay the picture in PictureBox placed in the Client Window. Here is a Code I am using to Send and Receive text BUT NOT PICTURE

服务器:

接收器:

void TListner()
    {
        try
        {
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            TcpListener tl = new TcpListener(ipendp);
            tl.Start();
            Socket s1 = tl.AcceptSocket(); ;
            NetworkStream ns = new NetworkStream(s1);
            StreamReader sr = new StreamReader(ns);

            while (true)
            {
                    textBox1.Text = sr.ReadLine();
            }
        }
        catch
        {
            Application.Exit();
        }

    }

发件人:

        MemoryStream ms = new MemoryStream();
        sw.Write("TEST STRING");
        sw.Flush();



客户端:

CLIENT:

接收器:

    void TCP_CLIENT()
    {
        try
        {
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            TcpClient tcpc = new TcpClient();
            tcpc.Connect(ipendp);
            NetworkStream ns = tcpc.GetStream();
            StreamReader sr = new StreamReader(ns);
            while (true)
            {
                textBox1.Text = sr.ReadLine();
            }
        }
        catch
        {
            Application.Exit();
        }



我要显示在一个名为 PBox1 在客户端窗口。

推荐答案

您正在查找要发送和接收文本,因为你使用的StreamReader 的StreamWriter 。那些处理的文本。您还没有实际显示你的代码的尝试的用于发送照片,但您基本的不得的使用阅读 / 作家,除非你是第一个执行某种额外的编码(如BASE64)。

You're find to send and receive text because you're using StreamReader and StreamWriter. Those deal with text. You haven't actually shown the code you're trying to use for sending pictures, but fundamentally you mustn't use Reader/Writer unless you're performing some sort of extra encoding first (e.g. base64).

另外除非你要发送后立即关闭写套接字,你应该写数据长度(例如,作为4字节)数据之前,以便接收插座知道多少需要接收。

Also, unless you're going to close the writing socket immediately after sending, you should probably write the data length (e.g. as 4 bytes) before the data so that the receiving socket knows how much it needs to receive.

这篇关于发送/ C#中接收图像通过TCP套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆