文章目录:
- 1、请教C#WinForm下的UDP代码
- 2、c#之UDP协议的异步通信怎么做
- 3、如何实现TCP和UDP传输
- 4、有没有windows下c语言实现udp协议的代码
- 5、UDP服务器设计。考虑到实时性,采用UDP协议,程序设计语言使用C语言,MFC库。
请教C#WinForm下的UDP代码
UDP和WINFORM没有半毛钱关系,
UDP是一种网络通讯协议,常用于单片机通讯或者底层通讯,不需要握手,
至于代码,不明白你到底要什么代码,一般来讲UDP需要声明服务端和客户端 ,并接受和发送数据,
思路上就是服务端声明自己的IP、 端口, 然后开启监听,
客户端向指定的IP端口发送数据,
当然服务端也可以发送,客户端也可以监听,
最需要处理的一般是异步接收后的操作,
下面是个简单的UDP通讯的代码,服务端功能基本如下,客户端可以比葫芦画瓢,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace UdpChatExample
{
/// summary
/// UDP服务器对象
/// /summary
public class UDPServerClass
{
public delegate void MessageHandler(string Message);//定义委托事件
public event MessageHandler MessageArrived;
public UDPServerClass()
{
//获取本机可用IP地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ipa in ips)
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{
MyIPAddress = ipa;//获取本地IP地址
break;
}
}
Note_StringBuilder = new StringBuilder();
PortName = 8080;
}
public UdpClient ReceiveUdpClient;
/// summary
/// 侦听端口名称
/// /summary
public int PortName;
/// summary
/// 本地地址
/// /summary
public IPEndPoint LocalIPEndPoint;
/// summary
/// 日志记录
/// /summary
public StringBuilder Note_StringBuilder;
/// summary
/// 本地IP地址
/// /summary
public IPAddress MyIPAddress;
public void Thread_Listen()
{
//创建一个线程接收远程主机发来的信息
Thread myThread = new Thread(ReceiveData);
myThread.IsBackground = true;
myThread.Start();
}
/// summary
/// 接收数据
/// /summary
private void ReceiveData()
{
IPEndPoint local = new IPEndPoint(MyIPAddress, PortName);
ReceiveUdpClient = new UdpClient(local);
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
//关闭udpClient 时此句会产生异常
byte[] receiveBytes = ReceiveUdpClient.Receive(ref remote);
string receiveMessage = Encoding.Default.GetString(receiveBytes, 0, receiveBytes.Length);
// receiveMessage = ASCIIEncoding.ASCII.GetString(receiveBytes, 0, receiveBytes.Length);
MessageArrived(string.Format("{0}来自{1}:{2}", DateTime.Now.ToString(), remote, receiveMessage));
//try
//{
// Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
// ReceiveUdpClient.Send(sendBytes, sendBytes.Length, local);
//}
//catch (Exception e)
//{
//}
//break;
}
catch
{
break;
}
}
}
/// summary
/// 添加日志信息到Note_StringBuilder
/// /summary
public void AddMessage_Note_StringBuilder()
{
}
}
}
c#之UDP协议的异步通信怎么做
UDP服务器:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleUdpServer
{
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
EndPoint localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8002);
socket.Bind(localEP);
//启动异步接收
State state = new State(socket);
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
Console.ReadLine();
socket.Close();
}
//异步接收回调函数
static void EndReceiveFromCallback(IAsyncResult iar)
{
State state = iar.AsyncState as State;
Socket socket = state.Socket;
try
{
//完成接收
int byteRead = socket.EndReceiveFrom(iar, ref state.RemoteEP);
//显示客户端地址和端口
Console.WriteLine("客户端终结点:{0}", state.RemoteEP.ToString());
//显示接收信息
Console.WriteLine("接收数据字节数:{0}", byteRead);
string message = Encoding.Default.GetString(state.Buffer, 0, byteRead);
Console.WriteLine("来着客户端信息:{0}", message);
//向客户端发送信息
SendMeaage(socket, state.RemoteEP, "成功接收!");
}
catch (Exception e)
{
Console.WriteLine("发生异常!异常信息:");
Console.WriteLine(e.Message);
}
finally
{
//非常重要:继续异步接收
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
}
}
/// summary
/// 向客户端发送信息
/// /summary
/// param name="socket"本地Socket(服务器Socket)/param
/// param name="remoteEndPoint"客户端终结点/param
/// param name="Message"信息/param
static void SendMeaage(Socket socket, EndPoint remoteEndPoint, string Message)
{
byte[] bytes = Encoding.Default.GetBytes(Message);
socket.SendTo(bytes, remoteEndPoint);
}
}
/// summary
/// 用于异步接收处理的辅助类
/// /summary
class State
{
public State(Socket socket)
{
this.Buffer = new byte[1024];
this.Socket = socket;
this.RemoteEP = new IPEndPoint(IPAddress.Any, 0);
}
/// summary
/// 获取本机(服务器)Socket
/// /summary
public Socket Socket { get; private set; }
/// summary
/// 获取接收缓冲区
/// /summary
public byte[] Buffer { get; private set; }
/// summary
/// 获取/设置客户端终结点
/// /summary
public EndPoint RemoteEP;
}
}
UDP客户端
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleUdpClient
{
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
//客户端使用的终结点
EndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
socket.Bind(localEP);
//启动异步接收
State state = new State(socket);
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
//向服务器发送信息
EndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8002);
SendMeaage(socket, remoteEP, "你好,这里是客户端,收到请回复!Over~~~~");
Console.ReadLine();
socket.Close();
}
//异步接收回调函数
static void EndReceiveFromCallback(IAsyncResult iar)
{
State state = iar.AsyncState as State;
Socket socket = state.Socket;
try
{
//完成接收
int byteRead = socket.EndReceiveFrom(iar, ref state.RemoteEP);
//显示服务器地址和端口
Console.WriteLine("服务器终结点:{0}", state.RemoteEP.ToString());
//显示接收信息
Console.WriteLine("接收数据字节数:{0}", byteRead);
string message = Encoding.Default.GetString(state.Buffer, 0, byteRead);
Console.WriteLine("来着服务器的信息:{0}", message);
}
catch (Exception e)
{
Console.WriteLine("发生异常!异常信息:");
Console.WriteLine(e.Message);
}
finally
{
//非常重要:继续异步接收
socket.BeginReceiveFrom(
state.Buffer, 0, state.Buffer.Length,
SocketFlags.None,
ref state.RemoteEP,
EndReceiveFromCallback,
state);
}
}
/// summary
/// 向服务器发送信息
/// /summary
/// param name="socket"本地Socket/param
/// param name="remoteEndPoint"服务器终结点/param
/// param name="Message"信息/param
static void SendMeaage(Socket socket, EndPoint remoteEndPoint, string Message)
{
byte[] bytes = Encoding.Default.GetBytes(Message);
socket.SendTo(bytes, remoteEndPoint);
}
}
/// summary
/// 用于异步接收处理的辅助类
/// /summary
class State
{
public State(Socket socket)
{
this.Buffer = new byte[1024];
this.Socket = socket;
this.RemoteEP = new IPEndPoint(IPAddress.Any, 0);
}
/// summary
/// 获取本机Socket
/// /summary
public Socket Socket { get; private set; }
/// summary
/// 获取接收缓冲区
/// /summary
public byte[] Buffer { get; private set; }
/// summary
/// 获取/设置客户端终结点
/// /summary
public EndPoint RemoteEP;
}
}
如何实现TCP和UDP传输
首先我们来看一下什么是TCP和UDP。
什么是TCP?
TCP:Transmission Control Protocol 传输控制协议TCP是一种面向连接(连接导向)的、可靠的、基于字节流的运输层(Transport layer)通信协议,由IETF的RFC 793说明(specified)。在简化的计算机网络OSI模型中,它完成第四层传输层所指定的功能。应用层向TCP层发送用于网间传输的、用8位字节表示的数据流,然后TCP把数据流分割成适当长度的报文段(通常受该计算机连接的网络的数据链路层的最大传送单元(MTU)的限制)。之后TCP把结果包传给IP层,由它来通过网络将包传送给接收端实体的TCP层。TCP为了保证不发生丢包,就给每个字节一个序号,同时序号也保证了传送到接收端实体的包的按序接收。然后接收端实体对已成功收到的字节发回一个相应的确认(ACK);如果发送端实体在合理的往返时延(RTT)内未收到确认,那么对应的数据(假设丢失了)将会被重传。TCP用一个校验和函数来检验数据是否有错误;在发送和接收时都要计算校验和。
首先,TCP建立连接之后,通信双方都同时可以进行数据的传输,其次,他是全双工的;在保证可靠性上,采用超时重传和捎带确认机制。
在流量控制上,采用滑动窗口协议[1],协议中规定,对于窗口内未经确认的分组需要重传。
在拥塞控制上,采用慢启动算法。
什么是UDP?
UDP 是User Datagram Protocol的简称, 中文名是用户数据包协议,是 OSI 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。它是IETF RFC 768是UDP的正式规范。在网络中它与TCP协议一样用于处理数据包。在OSI模型中,在第四层——传输层,处于IP协议的上一层。UDP有不提供数据报分组、组装和不能对数据包的排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。 UDP用来支持那些需要在计算机之间传输数据的网络应用。包括网络视频会议系统在内的众多的客户/服务器模式的网络应用都需要使用UDP协议。UDP协议从问世至今已经被使用了很多年,虽然其最初的光彩已经被一些类似协议所掩盖,但是即使是在今天,UDP仍然不失为一项非常实用和可行的网络传输层协议。
与所熟知的TCP(传输控制协议)协议一样,UDP协议直接位于IP(网际协议)协议的顶层。根据OSI(开放系统互连)参考模型,UDP和TCP都属于传输层协议。
UDP协议的主要作用是将网络数据流量压缩成数据报的形式。一个典型的数据报就是一个二进制数据的传输单位。每一个数据报的前8个字节用来包含报头信息,剩余字节则用来包含具体的传输数据。
TCP和UDP在android中的使用和在Java里是完全一样的。
首先我们看看TCP连接,下图为TCP连接的一个示意图:
TCP传输原理
是不是很好理解,这里就不多说了,直接看代码吧!实践出真知。
TCP服务器端代码:
try { Boolean endFlag = false; ServerSocket ss = new ServerSocket(12345); while (!endFlag) { // 等待客户端连接 Socket s = ss.accept(); BufferedReader input = new BufferedReader(newInputStreamReader(s.getInputStream())); //注意第二个参数据为true将会自动flush,否则需要需要手动操作output.flush() PrintWriter output = newPrintWriter(s.getOutputStream(),true); String message = input.readLine(); Log.d("Tcp Demo", "message from Client:"+message); output.println("message received!"); //output.flush(); if("shutDown".equals(message)){ endFlag=true; } s.close(); } ss.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
TCP客户端代码:
try { Socket s = new Socket("localhost", 12345); // outgoing stream redirect to socket OutputStream out = s.getOutputStream(); // 注意第二个参数据为true将会自动flush,否则需要需要手动操作out.flush() PrintWriter output = new PrintWriter(out, true); output.println("Hello IdeasAndroid!"); BufferedReader input = new BufferedReader(newInputStreamReader(s .getInputStream())); // read line(s) String message = input.readLine(); Log.d("Tcp Demo", "message From Server:" + message); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
下面我们看看UDP:
UDP传输原理
UDP服务器端代码:
// UDP服务器监听的端口 Integer port = 12345; // 接收的字节大小,客户端发送的数据不能超过这个大小 byte[] message = new byte[1024]; try { // 建立Socket连接 DatagramSocket datagramSocket = new DatagramSocket(port); DatagramPacket datagramPacket = new DatagramPacket(message, message.length); try { while (true) { // 准备接收数据 datagramSocket.receive(datagramPacket); Log.d("UDP Demo", datagramPacket.getAddress() .getHostAddress().toString() + ":" + new String(datagramPacket.getData())); } } catch (IOException e) { e.printStackTrace(); } } catch (SocketException e) { e.printStackTrace(); }
UDP客户端代码:
public static void send(String message) { message = (message == null ? "Hello IdeasAndroid!" : message); int server_port = 12345; DatagramSocket s = null; try { s = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } InetAddress local = null; try { // 换成服务器端IP local = InetAddress.getByName("localhost"); } catch (UnknownHostException e) { e.printStackTrace(); } int msg_length = message.length(); byte[] messagemessageByte = message.getBytes(); DatagramPacket p = new DatagramPacket(messageByte, msg_length, local, server_port); try { s.send(p); } catch (IOException e) { e.printStackTrace(); } }
代码中需要注意的地方已做了注释,希望本文对您有所帮助!
有没有windows下c语言实现udp协议的代码
Windows下C语言的Socket编程例子(TCP和UDP)
一。 TCP
server端:
复制代码
1 #include "stdafx.h"
2 #include stdio.h
3 #include winsock2.h
4
5 #pragma comment(lib,"ws2_32.lib")
6
7 int main(int argc, char* argv[])
8 {
9 //初始化WSA
10 WORD sockVersion = MAKEWORD(2,2);
11 WSADATA wsaData;
12 if(WSAStartup(sockVersion, wsaData)!=0)
13 {
14 return 0;
15 }
16
17 //创建套接字
18 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
19 if(slisten == INVALID_SOCKET)
20 {
21 printf("socket error !");
22 return 0;
23 }
24
25 //绑定IP和端口
26 sockaddr_in sin;
27 sin.sin_family = AF_INET;
28 sin.sin_port = htons(8888);
29 sin.sin_addr.S_un.S_addr = INADDR_ANY;
30 if(bind(slisten, (LPSOCKADDR)sin, sizeof(sin)) == SOCKET_ERROR)
31 {
32 printf("bind error !");
33 }
34
35 //开始监听
36 if(listen(slisten, 5) == SOCKET_ERROR)
37 {
38 printf("listen error !");
39 return 0;
40 }
41
42 //循环接收数据
43 SOCKET sClient;
44 sockaddr_in remoteAddr;
45 int nAddrlen = sizeof(remoteAddr);
46 char revData[255];
47 while (true)
48 {
49 printf("等待连接...\n");
50 sClient = accept(slisten, (SOCKADDR *)remoteAddr, nAddrlen);
51 if(sClient == INVALID_SOCKET)
52 {
53 printf("accept error !");
54 continue;
55 }
56 printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
57
58 //接收数据
59 int ret = recv(sClient, revData, 255, 0);
60 if(ret 0)
61 {
62 revData[ret] = 0x00;
63 printf(revData);
64 }
65
66 //发送数据
67 char * sendData = "你好,TCP客户端!\n";
68 send(sClient, sendData, strlen(sendData), 0);
69 closesocket(sClient);
70 }
71
72 closesocket(slisten);
73 WSACleanup();
74 return 0;
75 }
复制代码
client端:
复制代码
1 #include "stdafx.h"
2 #include WINSOCK2.H
3 #include STDIO.H
4
5 #pragma comment(lib,"ws2_32.lib")
6
7
8 int main(int argc, char* argv[])
9 {
10 WORD sockVersion = MAKEWORD(2,2);
11 WSADATA data;
12 if(WSAStartup(sockVersion, data) != 0)
13 {
14 return 0;
15 }
16
17 SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
18 if(sclient == INVALID_SOCKET)
19 {
20 printf("invalid socket !");
21 return 0;
22 }
23
24 sockaddr_in serAddr;
25 serAddr.sin_family = AF_INET;
26 serAddr.sin_port = htons(8888);
27 serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
28 if (connect(sclient, (sockaddr *)serAddr, sizeof(serAddr)) == SOCKET_ERROR)
29 {
30 printf("connect error !");
31 closesocket(sclient);
32 return 0;
33 }
34 char * sendData = "你好,TCP服务端,我是客户端!\n";
35 send(sclient, sendData, strlen(sendData), 0);
36
37 char recData[255];
38 int ret = recv(sclient, recData, 255, 0);
39 if(ret 0)
40 {
41 recData[ret] = 0x00;
42 printf(recData);
43 }
44 closesocket(sclient);
45 WSACleanup();
46 return 0;
47 }
复制代码
二. UDP
SERVER 端
复制代码
1 #include "stdafx.h"
2 #include stdio.h
3 #include winsock2.h
4
5 #pragma comment(lib, "ws2_32.lib")
6
7 int main(int argc, char* argv[])
8 {
9 WSADATA wsaData;
10 WORD sockVersion = MAKEWORD(2,2);
11 if(WSAStartup(sockVersion, wsaData) != 0)
12 {
13 return 0;
14 }
15
16 SOCKET serSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
17 if(serSocket == INVALID_SOCKET)
18 {
19 printf("socket error !");
20 return 0;
21 }
22
23 sockaddr_in serAddr;
24 serAddr.sin_family = AF_INET;
25 serAddr.sin_port = htons(8888);
26 serAddr.sin_addr.S_un.S_addr = INADDR_ANY;
27 if(bind(serSocket, (sockaddr *)serAddr, sizeof(serAddr)) == SOCKET_ERROR)
28 {
29 printf("bind error !");
30 closesocket(serSocket);
31 return 0;
32 }
33
34 sockaddr_in remoteAddr;
35 int nAddrLen = sizeof(remoteAddr);
36 while (true)
37 {
38 char recvData[255];
39 int ret = recvfrom(serSocket, recvData, 255, 0, (sockaddr *)remoteAddr, nAddrLen);
40 if (ret 0)
41 {
42 recvData[ret] = 0x00;
43 printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
44 printf(recvData);
45 }
46
47 char * sendData = "一个来自服务端的UDP数据包\n";
48 sendto(serSocket, sendData, strlen(sendData), 0, (sockaddr *)remoteAddr, nAddrLen);
49
50 }
51 closesocket(serSocket);
52 WSACleanup();
53 return 0;
54 }
复制代码
CLIENT 端
复制代码
1 #include "stdafx.h"
2 #include stdio.h
3 #include winsock2.h
4
5 #pragma comment(lib, "ws2_32.lib")
6
7 int main(int argc, char* argv[])
8 {
9 WORD socketVersion = MAKEWORD(2,2);
10 WSADATA wsaData;
11 if(WSAStartup(socketVersion, wsaData) != 0)
12 {
13 return 0;
14 }
15 SOCKET sclient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
16
17 sockaddr_in sin;
18 sin.sin_family = AF_INET;
19 sin.sin_port = htons(8888);
20 sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
21 int len = sizeof(sin);
22
23 char * sendData = "来自客户端的数据包.\n";
24 sendto(sclient, sendData, strlen(sendData), 0, (sockaddr *)sin, len);
25
26 char recvData[255];
27 int ret = recvfrom(sclient, recvData, 255, 0, (sockaddr *)sin, len);
28 if(ret 0)
29 {
30 recvData[ret] = 0x00;
31 printf(recvData);
32 }
33
34 closesocket(sclient);
35 WSACleanup();
36 return 0;
37 }
UDP服务器设计。考虑到实时性,采用UDP协议,程序设计语言使用C语言,MFC库。
基础很重要~~,UDP端对端通信基本代码
/*
#include winsock2.h
#pragma comment(lib,"WS2_32.lib")
*/
WSADATA wsd;
SOCKET s;
char buf[1024];
if(WSAStartup(MAKEWORD(2,2),wsd)!=0)
{
return -1;//失败
}
s=socket(AF_INET,SOCK_DGRAM,0);
if(s==INVALID_SOCKET)
{
WSACleanup();
return -1;//创建套接字失败
}
SOCKADDR_IN servAddr;
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=inet_addr(%%1);
servAddr.sin_port=htons(INADDR_ANY);
if(bind(s,(SOCKADDR*)servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR)
{
closesocket(s);
WSACleanup();
return -1;//绑定套接字失败
}
int nServAddrlen=sizeof(servAddr);
ZeroMemory(buf,sizeof(buf));
if(recvfrom(s,buf,sizeof(buf),0,(SOCKADDR*)servAddr,nServAddrlen)==SOCKET_ERROR)
{
closesocket(s);
WSACleanup();
return -1;//接收数据失败
}
CString %%2(buf);
ZeroMemory(buf,sizeof(buf));
strcpy(buf,%%3);
SOCKADDR_IN clientAddr;
clientAddr.sin_family=AF_INET;
clientAddr.sin_addr.s_addr=inet_addr(%%4);
clientAddr.sin_port=htons((short)%%5);
int nClientlen=sizeof(clientAddr);
if(sendto(s,buf,sizeof(buf),0,(SOCKADDR*)clientAddr,nClientlen)==SOCKET_ERROR)
{
closesocket(s);
WSACleanup();
return -1;//向服务器发送数据失败
}
closesocket(s);
WSACleanup();
summary /// 本地地址 /// /summary public IPEndPoint LocalIPEndPoint; /// summary /// 日志记录
t编程例子(TCP和UDP)一。 TCPserver端:复制代码 1 #include "stdafx.h" 2 #include stdio.h 3 #include winsock2.h 4 5 #pr