Socket怎么实现

发布网友 发布时间:2022-04-20 08:05

我来回答

3个回答

热心网友 时间:2022-05-13 04:34

客户端:
#include <winsock2.h>
#include "windows.h"
#include <stdio.h>
#include <string.h>
#pragma comment(lib,"ws2_32.lib")
void main(int argc, char* argv[])
{

WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}

if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}

SOCKET sock = socket(PF_INET,SOCK_STREAM,0);
if(sock==SOCKET_ERROR)
{
printf("sock create fail!\n");
closesocket(sock);
}
SOCKADDR_IN ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(80);
ser.sin_addr.s_addr=inet_addr("192.168.1.1");
if(connect(sock,(SOCKADDR*)&ser,sizeof(SOCKADDR))==SOCKET_ERROR) {
printf("Connect fail \n");
closesocket(sock);
exit(0);
}
/*char sendbuf[20];
printf("输入:");
gets(sendbuf);
send(sock,sendbuf,strlen(sendbuf)+1,0);*/
send(sock,"hello",strlen("hello")+1,0);
char recvBuf[20];
recv(sock,recvBuf,20,0);
printf("%s\n",recvBuf);

closesocket(sock);
WSACleanup();
}
server:
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>

#pragma comment(lib,"ws2_32.lib")
void main(int argc, char* argv[])
{

int len;

WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
printf("Error at WSAStartup()\n");

SOCKET sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd==SOCKET_ERROR)
{
printf("sockfd create fail!\n");
}
SOCKADDR_IN ser;
ser.sin_family = AF_INET;
ser.sin_port = htons(80);
ser.sin_addr.s_addr = htonl(INADDR_ANY);//任何ip主机都接收
if(bind(sockfd, (SOCKADDR *)&ser, sizeof(SOCKADDR))==SOCKET_ERROR)//绑定套接字
{
printf("bind is the error!!!");
}
if(listen(sockfd,10)==SOCKET_ERROR)
{
printf("error");
}
printf("Server %d is listening......\n",80);

SOCKADDR_IN cli;
len = sizeof(cli);
while(1)
{
printf("goodr");
SOCKET confd = accept(sockfd, (SOCKADDR *)&cli, &len);//confd用于处理网络连接
char sendBuf[100];
sprintf(sendBuf,"Welcome %s to here!",inet_ntoa(cli.sin_addr));
send(confd,sendBuf,strlen(sendBuf)+1,0);
char recvbuf[100];
recv(confd,recvbuf,100,0);
printf("%s\n",recvbuf);
closesocket(confd);

}

}
这个是我自己写的 也是初学者~这个能通过 但是似乎两端数据传送有点问题~我正在研究。有兴趣的话我们一起讨论~~

热心网友 时间:2022-05-13 05:52

看TCP/IP协议详解
准备自己做?

热心网友 时间:2022-05-13 07:27

在网上找个最简单的例程看看呗,我这有,VC6.0做的,需要的话联系我
声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:11247931@qq.com