利用TCP和UDP协议完成一个单机五子棋游戏。
封装TCP和UDP网络通信。
network.h
#ifndef NETWORK_H
#define NETWORK_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <netinet/in.h>
typedef struct sockaddr* SP;
#define MAX_LISTEN 50
#define error(func) fprintf(stderr,"%s:%d,%s:%m,pid:%u\n",__FILE__,__LINE__,func,getpid())
typedef struct NetWork
{
int fd; // socket对象描述符
int type; // SOCK_DGRAM或SOCK_STREAM
socklen_t len; // 地址结构的字节数
struct sockaddr_in addr; // 通信地址
}NetWork;
// 创建NetWork对象
NetWork* nopen(int type,const char* ip,in_port_t port,bool issvr);
// 用于接收客户端连接,TCP服务端专用
NetWork* naccept(NetWork* svrnw);
// UDP和TCP通用的数据发送函数
int nsend(NetWork* nw,const void* buf,size_t len);
// UDP和TCP通用的数据接收函数
int nrecv(NetWork* nw,void* buf,size_t len);
// 关闭socket并释放NetWork
void nclose(NetWork* nw);
#endif//NETWORK_H
network.c
#include <sys/socket.h>
#include <arpa/inet.h>
#include "network.h"
NetWork* nopen(int type,const char* ip,in_port_t port,bool issvr)
{
NetWork* nw = malloc(sizeof(NetWork));
if(NULL == nw)
{
error("malloc");
return NULL;
}
nw->fd = socket(AF_INET,type,0);
if(0 > nw->fd)
{
error("socket");
free(nw);
return NULL;
}
nw->type = type;
nw->len = sizeof(nw->addr);
nw->addr.sin_family = AF_INET;
nw->addr.sin_port = htons(port);
nw->addr.sin_addr.s_addr = inet_addr(ip);
if(issvr)
{
if(bind(nw->fd,(SP)&nw->addr,nw->len))
{
error("bind");
free(nw);
return NULL;
}
if(SOCK_STREAM == type && listen(nw->fd,MAX_LISTEN))
{
error