using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UdpClient
{
class Program
{
static void Main( string[] args)
{
byte[] data = new byte[1024];
string input, stringData;
Console.WriteLine( "这里是客户端, 主机名是 {0}", Dns.GetHostName());
//设置服务端IP,设置TCP端口号
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse( "192.168.1.125"), 8001);
//定义网络类型,数据连接类型和网络协议UDP
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "你好! ";
data = Encoding.UTF8.GetBytes( "客户端>>>" + welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep); //向服务端发送数据
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
//对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
//server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
int recv = server.ReceiveFrom(data, ref Remote); //将数据接收放入缓冲区
Console.WriteLine( "消息来自服务端 {0}: ", Remote.ToString());
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
while ( true)
{
input = Console.ReadLine();
//如果输入exit则退出
if (input == "exit" || input== "quit")
break;
//input = "客户端>>>" + input;
server.SendTo(Encoding.UTF8.GetBytes(input), Remote);
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);
stringData = Encoding.UTF8.GetString(data, 0, recv);
Console.Write( "服务端回复>>>");
Console.WriteLine(stringData);
}
Console.WriteLine( "客户端关闭.");
server.Close();
}
}
}