说明
- 本程序并没有区分服务端与客户端,只是调用函数不同
- 基于socket网络编程
- 第一次写,代码格式不怎么规范,请谅解
- 基于Linux,Win版本目前没写
- 接下来准备基于本程序搞一个更大的项目
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
#include <iostream>
const int MAXLINE = 4096;
const int PORT = 2726;
int sockfd, connfd; //sock句柄和连接句柄
struct sockaddr_in SerAddr;
char buf[MAXLINE];
int size;
using namespace std;
int ServerSockConn()
{
//检查连接并报错
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
cout << " Socket connect failed:" << errno << endl;
return 0;
}
//储存相关信息,如IP等
memset(&SerAddr, 0, sizeof(SerAddr));
SerAddr.sin_family = AF_INET;
SerAddr.sin_port = htons(PORT);
SerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//检测绑定并报错
if (bind(sockfd, (struct sockaddr*)&SerAddr, sizeof(SerAddr)) == -1)
{
cout << "Bind socket failed: " << errno << endl;
return 0;
}
//检测监听并报错
if( listen(sockfd, 10) == -1)
{
cout << "Listen socket failed: " << errno << endl;
return 0;
}
}
void GetInfor()
{
recv(connfd, buf, MAXLINE, 0);
cout << buf << endl;
close(connfd);
}
void SendInfor()
{
send(connfd, "Send", 15, 0);
}
//若为真则接收消息,若为假则发送消息
void ServerInfor(bool adj)
{
ServerSockConn();
while(1)
{
if ( (connfd = accept(sockfd, (struct sockaddr*)NULL,NULL)) == -1) //同意请求
{
cout << "Accept socket failed: " << errno << endl;
continue;
}
if (adj == true)
{
GetInfor();
}
else
{
SendInfor();
}
}
close(sockfd);
}
//客户端
int socketfd,n;
char recvline[MAXLINE], sendline[MAXLINE];
struct sockaddr_in CliAddr;
//真收,假发
int ClientInfor(bool adj)
{
socketfd = socket(AF_INET,SOCK_STREAM,0); //建立连接
if (socketfd == -1)
{
cout << "Socket failed:" << errno << endl;
}
CliAddr.sin_family=AF_INET;
CliAddr.sin_port=htons(PORT);
CliAddr.sin_addr.s_addr=inet_addr(""); //引号内为服务器公网IP
bzero(&(CliAddr.sin_zero),8);
if ( connect(socketfd,(struct sockaddr*)&CliAddr,sizeof(struct sockaddr)) == -1 ){
cout << "Connect failed:" << errno << endl;
}
else
{
if (adj == true)
{
recv(socketfd,buf,MAXLINE,0);
cout << buf << endl;
}
else
{
cout << "Please input" << endl;
send(socketfd,"conn",15,0);
close(socketfd);
}
}
}
int main()
{
//修改adjust变量来控制消息收发,为真则默认收,为假则发送
bool adjust = false;
/*
说明:
ClientInfor(); 为客户端使用
ServerInfor(); 为服务端使用
二者不能同时用,因为用了相同的buf变量
通过adjust变量作为函数参数来切换收发
*/
return 0;
}
网友评论