以下代码是TCP客户端的套接字编程示例。
但是当我运行它时,connect()被重新调整为协议不支持的地址族。 我正在尝试通过套接字进行服务器客户端通信。 首先我们向客户端发送一些字符串,然后我们从客户端读取一些字符串并打印出来。
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#define ADDRESS "mysocket"
char *str[3]={"dfgff","trer","ytt"};
int main()
{
char c;
FILE *fp;
register int i,s,ns,len;
int fromlen;
struct sockaddr saun,fsaun;
if((s=socket(AF_UNIX,SOCK_STREAM,0))<0)
{
perror("server:socket");
exit(1);
}
unlink("mysocket");
if (bind(s,&saun,sizeof(saun))<0)
{
perror("server: bind");
exit(1);
}
if (listen(s, 5) < 0)
{
perror("server: listen");
exit(1);
}
if ((ns = accept(s, &fsaun, NULL)) < 0)
{
perror("server: accept");
exit(1);
}
fdopen(ns, "r");
/*
* First we send some strings to the client.
for (i = 0; i <3 ; i++)
send(ns, str[i], strlen(str[i]), 0);
/*
* Then we read some strings from the client and
* print them out.
*/
for (i = 0; i <3; i++)
{
while ((c = fgetc(fp)) != EOF)
{
putchar(c);
if (c == '\n')
break;
}
}
close(s);
exit(0);
return 0;
}