题目要求:
通过C语言编写一个程序,程序中需要有两个进程,假设这两个进程是A和B,通过这两个进程模拟一个类似QQ聊天的情景,A进程和B进程分别代表通话一方,A进程能够发消息给B进程,同时还能接收B进程发送过来的消息,同样的,B进程能发送消息给A,同时接收A进程发送来的消息。
socket网络编程有几个步骤:
服务器:
1.socket()函数
2.bind()函数
3.listen()函数
4.accept()函数
5.read(),write(),close()等一系列文件相关的函数
客户端:
1.socket()函数
2.connect()函数
3.read(),write(),close()等一系列文件相关的函数
一、服务器代码:
Server.c:
#include<stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<string.h>
//头文件
int main(int argc,char **argv)
{
int s_fd;
int c_fd;
//定义两个socket描述符,一个客户端一个服务器的
char msg[128]={
0};
char readBuf[128]={
0};
//定义两个字符串数组一个用来接收另一个用来发送。
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
//定义两个sockaddr_in类型的结构体一个用于服务器一个客户端
if(argc!=3)
{
printf("Number Error!\n");
exit(-1);
}//我们运行程序的时候要输入三个变量,一个运行文件,一个IP地址,还有一个端口号(他们的定义在实验三里边有提到)
//socket
// int socket(int domain, int type, int protocol);
s_fd=socket(AF_INET,SOCK_STREAM,0);//第一个变量为协议 第二个为socket类型 第三个默认为0,表示自动匹配。
if(s_fd!=-1)
{
printf("Socket Success!\n");
}
else
<