a udp echo client

此博客介绍了与UdpEchoServer配合使用的UdpEchoClient,用于本机试验,设定接收时间限制为3秒。还给出了UdpEchoClient的代码,包含Socket创建、接收超时设置、数据发送与接收等操作,可通过输入“exit”停止客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

和我的UdpEchoServer配合使用,在本机上试验用。设定接收的时间限制是3秒。

/*
 * Created by SharpDevelop.
 * User: xuhx
 * Date: 2004-6-19
 * Time: 14:21
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

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

namespace DefaultNamespace
{
 /// <summary>
 /// Description of Class1. 
 /// </summary>
 public class UdpEchoClient
 {
  private static readonly int BUF_SIZE=2048;
  
  public static void Main(){
   Socket clientSocket=new Socket(AddressFamily.InterNetwork,
                                  SocketType.Dgram,
                                  ProtocolType.Udp
                                  );
   clientSocket.SetSocketOption(SocketOptionLevel.Socket,
                                 SocketOptionName.ReceiveTimeout,
                                 3000
                                 );
   EndPoint serverEndPoint=new IPEndPoint(IPAddress.Parse("127.0.0.1"),
                                          8004
                                          );
   Console.WriteLine("echo client start");
   while(true){
    string input=Console.ReadLine();
    if("exit"==input.ToLower()){
     clientSocket.Close();
     Console.WriteLine("echo client stop.");
     break;
    }
    byte[] buf=Encoding.ASCII.GetBytes(input);
    clientSocket.SendTo(buf,SocketFlags.None,serverEndPoint);
    buf=new byte[BUF_SIZE];
    EndPoint remoteEndPoint=new IPEndPoint(IPAddress.Any,0);
    try{
     int receive=clientSocket.ReceiveFrom(buf,ref remoteEndPoint);
     string strReceive=Encoding.ASCII.GetString(buf,0,receive);
     Console.WriteLine("echoed from server: {0} message:{1}",remoteEndPoint,strReceive);
    }catch(SocketException e){
     Console.WriteLine(e.Message);
    }
   }//while
  }
 }
}

转载于:https://www.cnblogs.com/xuhx/archive/2004/06/19/17135.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值