这里给出在linux下的简单的socket网络编程实例,使用tcp协议进行通信,服务端进行监听,再收到client的链接之后,发送数据给client;client在接收到数据后打印出来,然后关闭。程序里有具体的说明,当中对具体的结构体和函数的实现能够参照其他资料。
程序说明:这里的server的port和ip地址使用固定的设置,移植时能够依据详细情况更改,能够改写参数传递更好,这里为了更方便,使用固定的。
移植时服务端能够不用修改,编译后可以直接执行;client将ip改为server的地址,然后编译执行。能够使用netstat进行查看对应的执行状态。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
/*************************************
文件名称: server.c
linux 下socket网络编程简例 - 服务端程序
serverport设为 0x8888 (port和地址可依据实际情况更改,或者使用參数传入)
server地址设为 192.168.1.104
作者:kikilizhm#163.com (将#换为@)
*/
#
include
<stdlib.h>
#
include
<sys/types.h>
#
include
<stdio.h>
#
include
<sys/socket.h>
#
include
<linux/
in
.h>
#
include
<string.h>
int
main()
{
int
sfp,nfp;
/* 定义两个描写叙述符 */
struct sockaddr_in s_add,c_add;
int
sin_size;
unsigned short portnum=
0x8888
;
/* 服务端使用端口 */
printf(
"Hello,welcome to my server !\r\n"
);
sfp = socket(AF_INET, SOCK_STREAM,
0
);
if
(-
1
== sfp)
{
printf(
"socket fail ! \r\n"
);
return
-
1
;
}
printf(
"socket ok !\r\n"
);
/* 填充serverport地址信息,以便以下使用此地址和port监听 */
bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family=AF_INET;
s_add.sin_addr.s_addr=htonl(INADDR_ANY);
/* 这里地址使用全0,即全部 */
s_add.sin_port=htons(portnum);
/* 使用bind进行绑定port */
if
(-
1
== bind(sfp,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
{
printf(
"bind fail !\r\n"
);
return
-
1
;
}
printf(
"bind ok !\r\n"
);
/* 開始监听对应的port */
if
(-
1
== listen(sfp,
5
))
{
printf(
"listen fail !\r\n"
);
return
-
1
;
}
printf(
"listen ok\r\n"
);
while
(
1
)
{
sin_size = sizeof(struct sockaddr_in);
/* accept服务端使用函数,调用时即进入堵塞状态,等待用户进行连接,在没有client进行连接时,程序停止在此处,
不会看到后面的打印,当有client进行连接时,程序立即运行一次,然后再次循环到此处继续等待。
此处accept的第二个參数用于获取client的port和地址信息。
*/
nfp = accept(sfp, (struct sockaddr *)(&c_add), &sin_size);
if
(-
1
== nfp)
{
printf(
"accept fail !\r\n"
);
return
-
1
;
}
printf(
"accept ok!\r\nServer start get connect from %#x : %#x\r\n"
,ntohl(c_add.sin_addr.s_addr),ntohs(c_add.sin_port));
/* 这里使用write向client发送信息,也能够尝试使用其它函数实现 */
if
(-
1
== write(nfp,
"hello,welcome to my server \r\n"
,
32
))
{
printf(
"write fail!\r\n"
);
return
-
1
;
}
printf(
"write ok!\r\n"
);
close(nfp);
}
close(sfp);
return
0
;
}
|