C#中服务器客户端应用程序的UDP数据报代码 [英] UDP datagram code for server client application in C#

查看:23
本文介绍了C#中服务器客户端应用程序的UDP数据报代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从我的客户端发送消息时,服务器无法接收该消息并打印它.谁能告诉我以下服务器客户端应用程序中的错误.

When i try to send a message from my client , the server is not able to receive that message and print it. Can anyone tell me the error in the following server client application.

我创建了两个 WinForm 项目,一个是 UDP 服务器,另一个是 UDP 客户端.

I have created two WinForm projects, one is UDP server and the other is UDP client.

在 UDP 服务器项目中,我创建了一个表单,其中包含一个名为 RichTextBox1 的 RichTextBox 来显示消息和一个名为 btStart 的按钮来启动/停止侦听.这是代码片段:

In UDP server project, I created a form which contains a RichTextBox named richTextBox1 to show message and a Button named btStart to start/stop the listening. This is the code snippet:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace UDPServer
{
public partial class Form1 : Form
{
    delegate void ShowMessageMethod(string msg);

    UdpClient _server = null;
    IPEndPoint _client = null;
    Thread _listenThread = null;
    private bool _isServerStarted = false;

    public Form1()
    {
        InitializeComponent();
    }
    private void serverMsgBox_Load(object sender, EventArgs e)
    {
        this.btStart.Text = "StartServer";
    } 

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void btStart_Click(object sender, EventArgs e)
    {
        if (_isServerStarted)
        {
            Stop();
            btStart.Text = "StartServer";
        }
        else
        {
            Start();
            btStart.Text = "StopServer";
        }

    }
    private void Start()
    {
        //Create the server.
        IPEndPoint serverEnd = new IPEndPoint(IPAddress.Any, 1234);
        _server = new UdpClient(serverEnd);
        ShowMsg("Waiting for a client...");
        //Create the client end.
        _client = new IPEndPoint(IPAddress.Any, 0);

        //Start listening.
        Thread listenThread = new Thread(new ThreadStart(Listening));
        listenThread.Start();
        //Change state to indicate the server starts.
        _isServerStarted = true;
    }

    private void Stop()
    {
        try
        {
            //Stop listening.
            listenThread.Join();
            ShowMsg("Server stops.");
            _server.Close();
            //Changet state to indicate the server stops.
            _isServerStarted = false;
        }
        catch (Exception excp)
        { }
    }

    private void Listening()
    {
        byte[] data;
        //Listening loop.
        while (true)
        {
            //receieve a message form a client.
            data = _server.Receive(ref _client);
            string receivedMsg = Encoding.ASCII.GetString(data, 0, data.Length);
            //Show the message.
            this.Invoke(new ShowMessageMethod(ShowMsg), new object[] { "Client:" + receivedMsg });
            //Send a response message.
            data = Encoding.ASCII.GetBytes("Server:" + receivedMsg);
            _server.Send(data, data.Length, _client);
            //Sleep for UI to work.
            Thread.Sleep(500);
        }
    }
    private void ShowMsg(string msg)
    {
        this.richTextBox1.Text += msg + "\r\n";
    }
}
}

在UDP客户端项目中,我还创建了一个表单,其中包含一个名为richTextBox1的RichTextBox来输入或显示消息,以及一个名为btSend的按钮来发送输入消息.您可以运行此项目的多个实例.服务器将处理所有正在运行的客户端.这是代码片段:

In UDP client project, I also created a form which contains a RichTextBox named richTextBox1 to input or show message and a Button named btSend to send the input message. You can run several instances of this project. The server would cope with all the running clients. This is the code snippet:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace UDPClient
{
public partial class Form1 : Form
{
    UdpClient _server = null;
    IPEndPoint _client = null;

    public Form1()
    {
        InitializeComponent();
    }



    private void Form1_Load(object sender, EventArgs e)
    {

    }
   private void serverMsgBox_Load(object sender, EventArgs e)
    {
        //Get the server.
        _server = new UdpClient("127.0.0.1", 16000);
        //Create a client.
        _client = new IPEndPoint(IPAddress.Any, 0);
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        try
        {
            _server.Close();
        }
        catch (Exception s)
        { 
        }
    }

    private void btSend_Click(object sender, EventArgs e)
    {
        try
        {
            //Send the input message.
            string text = this.richTextBox1.Text;
            _server.Send(Encoding.ASCII.GetBytes(text), text.Length);
            //Receive the response message.
            byte[] data = _server.Receive(ref _client);
            string msg = Encoding.ASCII.GetString(data, 0, data.Length);
            //Show the response message.
            this.richTextBox1.Text = msg;
        }
        catch (Exception exp)
        { 

        }
    }

}
}

推荐答案

您没有设置目的地.您需要在使用 UdpClient.Connect 之前使用 UdpClient.Connecthttp://msdn.microsoft.com/en-us/library/08h8s12k.aspx" rel="nofollow">UdpClient.Send(Byte[], Int32) 或使用 UdpClient.Send(Byte[], Int32, IPEndPoint).

You are not setting your destination. You need to either use UdpClient.Connect before using UdpClient.Send(Byte[], Int32) or use UdpClient.Send(Byte[], Int32, IPEndPoint).

这篇关于C#中服务器客户端应用程序的UDP数据报代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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