UDP datagram code for server client application in C#

末鹿安然 提交于 2019-12-10 22:36:55

问题


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.

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

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";
    }
}
}

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)
        { 

        }
    }

}
}

回答1:


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).



来源:https://stackoverflow.com/questions/10076658/udp-datagram-code-for-server-client-application-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!