提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、linux socket 学习和编写?
主要目的是使用vs 调试linux socket程序(直接linux上可以运行)。服务器端循环接收客户端消息,发送消息给客户端,客户端同样发送和接收消息。循环建立连接。使用vs 调试linux程序,具体可以参考 linux c程序编写工具(使用visual studio)
二、直接上代码
/* 服务器端 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int socket_test(void);
int main() {
while(1){
socket_test();
sleep(1);
}
}
int cnt = 1;
int socket_test(void) {
int err = 0;
//创建套接字
int client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client < 0)
{
printf("client : create socket error\n");
return 1;
}
//配置连接IP和端口
struct sockaddr_in client_addr = { 0 };
client_addr.sin_family = AF_INET; //使用IPv4地址
client_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
client_addr.sin_port = htons(1234); //端口
//连接
err = connect(client, (struct sockaddr*)&client_addr, sizeof(client_addr));
if (err == 0) {
printf("client : connect to server\n");
}
else {
printf("client : connect error\n");
return -1;
}
printf("connect!\r\n");
//读取服务器传回的数据
char buffer[40] = { 0 };
read(client, buffer, sizeof(buffer) - 1);
printf(">>%d<<Message form server: %s\n", cnt, buffer);
/* 发送数据给服务器 */
char str[200] = { 0 };
sprintf(str, "这是客户端第%d条数据", cnt);
write(client, str, strlen(str));
printf("写入%d个\r\n", cnt);
cnt++;
close(client);
return 0;
}
/* 客户端 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int socket_test(void);
int main() {
while (1) {
socket_test();
sleep(1);
}
}
int cnt = 1;
int socket_test(void) {
printf("欢迎使用本服务器!!my\r\n");
int err; //返回值
int accp = 0;
//创建套接字
int sever = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sever < 0)
{
printf("server : server socket create error\n");
return -1;
}
int on = 1;
int s = setsockopt(sever, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (s < 0) {
printf("server : setsockopt error\n");
return -1;
}
//初始化id端口号
struct sockaddr_in serv_addr = { 0 };
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
serv_addr.sin_port = htons(1234);
err = bind(sever, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if (err < 0)
{
printf("server : bind error\n");
return -1;
}
//监听
err = listen(sever, SOMAXCONN);
if (err < 0)
{
printf("server : listen error\n");
return -1;
}
//连接任务//处理数据接受
struct sockaddr_in clnt_addr = { 0 };
socklen_t clnt_addr_len = sizeof(clnt_addr);
accp = accept(sever, (struct sockaddr*)&clnt_addr, &clnt_addr_len);
if (accp > 0) {
printf("sever : accept!\n");
}else {
printf("sever : accept error\n");
return -1;
}
printf("sever connect!!\r\n");
/* 发送数据给客户端 */
char str[200] = { 0 };
sprintf(str, "这是服务器第%d条数据", cnt);
write(accp, str, strlen(str));
printf("写入%d个\r\n", cnt);
//读取客户端传回的数据
char buffer[40] = { 0 };
read(accp, buffer, sizeof(buffer) - 1);
printf(">>%d<<Message form server: %s\n", cnt, buffer);
cnt++;
close(accp);
close(sever);
return 0;
}
三、效果图示