C#服务器和客户端通信 - 发送/接收数据

时间:2017-03-27 20:22:05

标签: c# send

我需要帮助,我想制作服务器和客户端,他们将一起沟通。(发送/接收数据)

示例:当我登录并且服务器检查并向客户端发送(正确或不正确)时,客户端向服务器发送用户名和密码。

服务器和客户端可以一起发送和接收数据以及更多数据(例如:用户名,密码......在一次通信中)

我需要您与客户端,服务器通信的最佳示例,目前我有youtube的此脚本:enter link description here

有来自youtube的发送/接收方法:

public class PacketWriter : BinaryWriter
{
    // This will hold our packet bytes.
    private MemoryStream _ms;

    // We will use this to serialize (Not in this tutorial)
    private BinaryFormatter _bf;

    public PacketWriter() : base()
    {
        // Initialize our variables
        _ms = new MemoryStream();
        _bf = new BinaryFormatter();

        // Set the stream of the underlying BinaryWriter to our memory stream.
        OutStream = _ms;
    }

    public void Write(Image image)
    {
        var ms = new MemoryStream(); //Create a memory stream to store our image bytes.

        image.Save(ms, ImageFormat.Png); //Save the image to the stream.

        ms.Close(); //Close the stream.

        byte[] imageBytes = ms.ToArray(); //Grab the bytes from the stream.

        //Write the image bytes to our memory stream
        //Length then bytes
        Write(imageBytes.Length);
        Write(imageBytes);
    }

    public void WriteT(object obj)
    {
        //We use the BinaryFormatter to serialize our object to the stream.
        _bf.Serialize(_ms, obj);
    }

    public byte[] GetBytes()
    {
        Close(); //Close the Stream. We no longer have need for it.

        byte[] data = _ms.ToArray(); //Grab the bytes and return.

        return data;
    }
}

public class PacketReader : BinaryReader
{
    // This will be used for deserializing
    private BinaryFormatter _bf;

    public PacketReader(byte[] data) : base(new MemoryStream(data))
    {
        _bf = new BinaryFormatter();
    }

    public Image ReadImage()
    {
        //Read the length first as we wrote it.
        int len = ReadInt32();
        //Read the bytes
        byte[] bytes = ReadBytes(len);

        Image img; //This will hold the image.

        using (MemoryStream ms = new MemoryStream(bytes))
        {
            img = Image.FromStream(ms); //Get the image from the stream of the bytes.
        }

        return img; //Return the image.
    }

    public T ReadObject<T>()
    {
        //Use the BinaryFormatter to deserialize the object and return it casted as T
        /* MSDN Generics
         * http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx
         */
        return (T)_bf.Deserialize(BaseStream);
    }
}

我不知道这是不是更好的方法,我没有经验,所以我想问一个更有经验的人。

好的方法是从数据制作图像并发送吗?

感谢您的任何建议,我将不胜感激!

1 个答案:

答案 0 :(得分:1)

查看this CodeProject example,这似乎是您正在寻找的内容。您需要两个单独的应用程序,一个用于您的服务器,另一个用于您的客户端。

服务器:基本上你需要做的就是打开一个TcpListener并从中接收字节。来自CodeProject的文章:

    using System;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;

    public class serv {
        public static void Main() {
        try {
            IPAddress ipAd = IPAddress.Parse("172.21.5.99");
             // use local m/c IP address, and 
             // use the same in the client

    /* Initializes the Listener */
            TcpListener myList=new TcpListener(ipAd,8001);

    /* Start Listening at the specified port */        
            myList.Start();

            Console.WriteLine("The server is running at port 8001...");    
            Console.WriteLine("The local End point is  :" + 
                              myList.LocalEndpoint );
            Console.WriteLine("Waiting for a connection.....");

            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b=new byte[100];
            int k=s.Receive(b);
            Console.WriteLine("Recieved...");
            for (int i=0;i<k;i++)
                Console.Write(Convert.ToChar(b[i]));

            ASCIIEncoding asen=new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");
            s.Close();
            myList.Stop();
        }
        catch (Exception e) {
            Console.WriteLine("Error..... " + e.StackTrace);
        }    
    }        
}

客户端:客户端非常相似,除了使用TcpListener之外,您还使用了TcpClient。再次来自CodeProject:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;


public class clnt {

    public static void Main() {

        try {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");

            tcpclnt.Connect("172.21.5.99",8001);
            // use the ipaddress as in the server program

            Console.WriteLine("Connected");
            Console.Write("Enter the string to be transmitted : ");

            String str=Console.ReadLine();
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen= new ASCIIEncoding();
            byte[] ba=asen.GetBytes(str);
            Console.WriteLine("Transmitting.....");

            stm.Write(ba,0,ba.Length);

            byte[] bb=new byte[100];
            int k=stm.Read(bb,0,100);

            for (int i=0;i<k;i++)
                Console.Write(Convert.ToChar(bb[i]));

            tcpclnt.Close();
        }

        catch (Exception e) {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }
}

这是一个非常基本的例子,说明如何在.Net中完成一些简单的网络任务;如果您计划创建基于Web的应用程序,我建议您使用WCF / Asp.Net。