一。 <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和WINFORM没有半毛钱关系,
UDP是一种网络通讯协议,常用于单片机通讯或者底层通讯,不需要握手,
至于代码,不明白你到底要什么代码,一般来讲UDP需要声明服务端和客户端 ,并接受和发送数据,
思路上就是服务端声明自己的IP、 端口, 然后开启监听,
客户端向指定的IP端口发送数据,
当然服务端也可以发送,客户端也可以监听,
最需要处理的一般是异步接收后的操作,
下面是个简单的UDP通讯的代码,服务端功能基本如下,客户端可以比葫芦画瓢,
using Systemusing 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()
{
}
}
}
我的是包含的#include <sys/socket.h>,参考一下吧<udp_client.c>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(void)
{
int sfdchar buf[1024]int n, i
struct sockaddr_in serv_addr, cli_addr
socklen_t len
sfd = socket(AF_INET, SOCK_DGRAM, 0)
memset(&serv_addr, 0, sizeof(serv_addr))
serv_addr.sin_family = AF_INET
serv_addr.sin_port = htons(8000)
inet_pton(AF_INET, "192.168.0.36", &serv_addr.sin_addr.s_addr)
while(1) {
if(fgets(buf, 1024, stdin) == NULL)
break
sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr))
n = recvfrom(sfd, buf, 1024, 0, NULL, NULL)
write(STDOUT_FILENO, buf, n)
}
close(sfd)
return 0
}
<udp_server.c>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(void)
{
int sfdchar buf[1024]int n, i
struct sockaddr_in serv_addr, cli_addr
socklen_t len
sfd = socket(AF_INET, SOCK_DGRAM, 0)
memset(&serv_addr, 0, sizeof(serv_addr))
serv_addr.sin_family = AF_INET
serv_addr.sin_port = htons(8000)
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY)
bind(sfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))
while(1) {
len = sizeof(cli_addr)
n = recvfrom(sfd, buf, 1024, 0, (struct sockaddr *)&cli_addr, &len)
for(i = 0i <ni++)
buf[i] = toupper(buf[i])
sendto(sfd, buf, n, 0, (struct sockaddr *)&cli_addr, len)
}
close(sfd)
return 0
}
请求采纳,谢谢!
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)