vc++ 6.0下运行代码
server端:
#include <string.h>
#include <winsock.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
const int SERVER_PORT = 3333;
const int MAX_ACCEPT = 10;
void server()
{
int sock_fd;
int client_fd;
struct sockaddr_in my_addr;//本机地址信息
struct sockaddr_in remote_addr;//客户端地址信息
int sin_size = 0;
char msg[20] = "欢迎登陆";
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2,1);
err = WSAStartup( wVersionRequested,&wsaData);
//建立面向连接的socket
if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) == -1){
printf("socket create error\n");
}
//各种参数的初始化
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(SERVER_PORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(my_addr.sin_zero),0,8);
//绑定端口
if(bind(sock_fd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr))== -1)
{
printf("socket bind error\n");
exit(1);
}
if(listen(sock_fd,MAX_ACCEPT)==-1)
{//监听端口
printf("socket listen error\n");
exit(1);
}
while(1)
{
//接受用户连接
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sock_fd,(struct sockaddr *)&remote_addr,&sin_size))==-1)
{
printf("accept error\n");
exit(1);
}
scanf("%s",msg);//服务器要向客户端发送的数据
//发送数据到客户端
if(send(client_fd,msg,strlen(msg),0)== -1)
{
printf("send error\n");
closesocket(client_fd);
exit(1);
}
closesocket(client_fd);//关闭端口
}
}
void main()
{
server();
}
client:
#pragma comment(lib,"ws2_32.lib")
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock.h>
const int SERVER_PORT = 3333;
const int MAXDATASIZE =100;
void client()
{
int sockfd;
int recvbytes;
char buf[MAXDATASIZE] = {0};
struct hostent * host;
struct sockaddr_in serv_addr;
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(2,1);
err = WSAStartup(wVersionRequested,&wsaData);
if((host=gethostbyname("localhost"))==NULL) {
printf("gethostbyname出错!");
exit(1);
}
if((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1)
{
printf("socket create error\n");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERVER_PORT);
serv_addr.sin_addr= *((struct in_addr *)host->h_addr);
memset(&(serv_addr.sin_zero),0,8);
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))== -1)
{
printf("connect error\n");
exit(1);
}
if((recvbytes=recv(sockfd,buf,MAXDATASIZE,0))==-1)
{
printf("recv error\n");
exit(1);
}
buf[recvbytes] = '\0';
printf("Received: %s\n",buf);
closesocket(sockfd);
}
void main(int argc ,char *argv[])
{
while(1)
{
client();
}
}
先运行服务器程序,再运行客户端程序,然后在服务器端输入数据,此时客户端就能收到数据了