📄 test1.cpp
字号:
// UDP_Winsock_API_Server_5000.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#define socklen_t int
#pragma comment(lib, "wsock32.lib")
//SOCKET sock;
sockaddr_in serv;
int addlen,s=1;
char buff[100];
int main(int argc, char* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return 1;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return 1;
}
/* The WinSock DLL is acceptable. Proceed. */
SOCKET sock;
char* buf="Client A speeking",buf1[1000];
int len,flags = MSG_DONTROUTE,k=0;
sock=socket(AF_INET,SOCK_DGRAM,0);
// serv.sin_addr.s_addr=htonl(INADDR_ANY);
serv.sin_addr.s_addr=inet_addr("127.0.0.1");
serv.sin_family=AF_INET;
serv.sin_port=3000;//htons(5000);
addlen=sizeof(serv);
while(k++<2 && (len=strlen(buf))>0){
if(sendto( sock, buf, len, flags, (sockaddr*)&serv, addlen)<0)
{
printf("\n发送错误:%d\n",WSAGetLastError());
return 0;
}
printf("\n发送成功");
if(recvfrom( sock, buf1, 1000, 0, (sockaddr*)&serv, &addlen)<0)
{
printf("\n接收错误:%d\n",WSAGetLastError());
//return 0;
}
printf("\nserver say:%s",buf1);
// scanf("%s",buf);
}
// if (bind(sock,(sockaddr*)&serv,addlen))
// {
// printf("\n绑定错误:%d\n",WSAGetLastError());
// }else
// {
// printf("\n服务器创建成功\n");
// //开始侦听
// while(s!=0)
// {
// s=recv(sock,buff,100,0);
// printf("\n%s",buff);
// }
// send(dlg->msgsock[msgcount],"Disconnected",100,0);
// }
closesocket(sock);
scanf("%s",buf);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -