基于vs2015实现udp通信
简单控制台程序
-
C#编写一个控制台程序,输出50行文字
①vs2015下编写代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace th7
{
class Program
{
static void Main(string[] args)
{
String str = "Hello Cqjtu !重交物联2018级";
int a = 0;
for(a=0;a<50;a++)
{
Console.WriteLine("the "+a+": "+str);
}
Console.ReadLine();
从0开始到49,依次输出50行文字。
-
线程实现控制台程序与udp通信
①服务端th7server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace th7sever
{
class Program
{
static void Main(string[] args)
{
String str = "Hello Cqjtu !重交物联2018级";
int a = 0;
for (a = 0; a < 50; a++)
{
Console.WriteLine("the " + a + ": " + str);
}
Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
IPEndPoint point = new IPEndPoint(ip, 2333);
//socket绑定监听地址
serverSocket.Bind(point);
Console.WriteLine("Listen Success");
//设置同时连接个数
serverSocket.Listen(10);
//利用线程后台执行监听,否则程序会假死
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(serverSocket);
Console.Read();
}
/// <summary>
/// 监听连接
/// </summary>
/// <param name="o"></param>
static void Listen(object o)
{
var serverSocket = o as Socket;
while (true)
{
//等待连接并且创建一个负责通讯的socket
var send = serverSocket.Accept();
//获取链接的IP地址
var sendIpoint = send.RemoteEndPoint.ToString();
Console.WriteLine($"{sendIpoint}Connection");
//开启一个新线程不停接收消息
Thread thread = new Thread(Recive);
thread.IsBackground = true;
thread.Start(send);
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="o"></param>
static void Recive(object o)
{
var send = o as Socket;
while (true)
{
//获取发送过来的消息容器
byte[] buffer = new byte[1024 * 1024 * 2];
var effective = send.Receive(buffer);
//有效字节为0则跳过
if (effective == 0)
{
break;
}
var str = Encoding.UTF8.GetString(buffer, 0, effective);
Console.WriteLine(str);
var buffers = Encoding.UTF8.GetBytes("Server Return Message");
send.Send(buffers);
}
}
}
②客户端th7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace th7
{
class Program
{
static void Main(string[] args)
{
String str = "Hello Cqjtu !重交物联2018级";
int a = 0;
for(a=0;a<50;a++)
{
Console.WriteLine("the "+a+": "+str);
}
//创建实例
Socket socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse("192.168.0.111");
IPEndPoint point = new IPEndPoint(ip, 2333);
//进行连接
socketClient.Connect(point);
//不停的接收服务器端发送的消息
Thread thread = new Thread(Recive);
thread.IsBackground = true;
thread.Start(socketClient);
//不停的给服务器发送数据
int i = 0;
while (true)
{
i++;
var buffter = Encoding.UTF8.GetBytes($"Test Send Message:{i}");
var temp = socketClient.Send(buffter);
Thread.Sleep(1000);
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="o"></param>
static void Recive(object o)
{
var send = o as Socket;
while (true)
{
//获取发送过来的消息
byte[] buffer = new byte[1024 * 1024 * 2];
var effective = send.Receive(buffer);
if (effective == 0)
{
break;
}
var str = Encoding.UTF8.GetString(buffer, 0, effective);
Console.WriteLine(str);
}
}
}
}
③结果展示
参考简单u的控制台pd通信
windows应用程序
- vs2015下C#编写一个form窗口实现udp通信
①服务端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace ser1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建端口对象
IPEndPoint point = new IPEndPoint(IPAddress.Any, 8888);
//监听
socketWatch.Bind(point);
ShowMsg("监听成功");
//某一时间点最大能监听的数,大于设置的数要排队
socketWatch.Listen(10);
//开启线程,不停的监听客户端的连接
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
}
catch (SocketException ex)
{
ShowMsg(ex.ToString());
return;
}
}
void ShowMsg(string str)
{
textBox1.AppendText(str + "\r\n");
}
void Listen(object o)
{
//线程中的参数只能是object
Socket socketWatch = o as Socket;
while (true)
{
try
{
//等待连接,连接成功返回一个用于数据收发得socket,while循环可以让不同得客户端连接
Socket socketSend = socketWatch.Accept();
//连接成功后,返回每一个客户端的 IP和port
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + " 连接成功" + "\r\n");
//开启新线程不停的接收客户端发来的消息
Thread th = new Thread(DataReceive);
th.IsBackground = true;
th.Start(socketSend);
}
catch (SocketException e)
{
ShowMsg(e.ToString());
break;
}
}
}
void DataReceive(object o)
{
Socket socketSend = o as Socket;
//不停的接收消息
while (true)
{
try
{
//定义接收缓存
byte[] bufferReceive = new byte[1024 * 1024 * 2];
//接收的字节数,当客户端下线时,receiveNumber=0
int receiveNumber = socketSend.Receive(bufferReceive);
//判断客户端是否下线,防止客户端下线时,服务端一直接收空消息
if (receiveNumber == 0)
{
break;
}
//字节转换成字符串
string str = Encoding.UTF8.GetString(bufferReceive, 0, receiveNumber);
//打印到窗体
ShowMsg(socketSend.RemoteEndPoint + ": " + str);
}
catch (SocketException e)
{
ShowMsg(e.ToString());
break;
}
}
}
Socket socketSend;
private void buttonSend_Click(object sender, EventArgs e)
{
string str = textBox2.Text.Trim();
//创建发送缓冲区
byte[] sendMessage = System.Text.Encoding.UTF8.GetBytes(str);
//给客户端发送消息
socketSend.Send(sendMessage); ;
}
}
}
②客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace cl1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Socket socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPEndPoint point = new IPEndPoint(IPAddress.Parse("10.62.23.50"), 8888);
socketSend.Connect(point);
ShowMsg("连接成功!");
Thread th = new Thread(ReceiveData);
th.IsBackground = true;
th.Start();
}
catch (SocketException ex)
{
ShowMsg(ex.ToString());
}
}
void ShowMsg(string str)
{
textBox1.AppendText(str + "\r\n");
}
/// <summary>
/// 接收服务端
/// </summary>
void ReceiveData(object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
byte[] receiveMessage = new byte[1024 * 1024 * 2];
//接收的字节数
int receiveNumber = socketSend.Receive(receiveMessage);
if (receiveNumber == 0)
{
break;
}
//字节转换成字符串
string str = Encoding.UTF8.GetString(receiveMessage, 0, receiveNumber);
//打印到窗体
ShowMsg(socketSend.RemoteEndPoint + ": " + str);
}
catch (SocketException e)
{
ShowMsg(e.ToString());
}
}
}
Socket socketSend;
private void buttonSend_Click(object sender, EventArgs e)
{
try
{
string str = textBox2.Text.Trim();
byte[] sendMessage = System.Text.Encoding.UTF8.GetBytes(str);
//给服务端发送消息
socketSend.Send(sendMessage);
textBox2.Text = "";
}
catch (SocketException ex)
{
ShowMsg(ex.ToString());
}
}
}
}
服务器端:一、创建服务器套接字(socket)。
二、服务器套接字进行信息绑定(bind),并开始监听连接(listen)。
三、接受来自用户端的连接请求(accept)。
四、开始数据传输(send/receive)。
客户端:一、创建客户套接字(socket)。
二、与远程服务器进行连接(connect),如被接受则创建接收进程。
三、开始数据传输(send/receive)。
结果展示
- wireshark抓包
可以看出UDP数据帧有源端口号、目的端口号、长度、校验和四个字段,其中UDP的协议号为17,十六进制为0X11。
总结+参考
在遇到问题查找资料的过程中了解到TCP协议相互连接时需要握手,因此UDP协议连接更加方便,但因为它的安全性也不是任何地方都可以用到UDP协议的。