#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/prctl.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <errno.h>
#include <ctype.h>
#include "common.h"
#include "message.h"
int safe_send(int __fd, const void *__buf, size_t __n, int __flags) {
int __snd = 0;
int __off = 0;
int __rem = __n;
while (__rem > 0) {
__snd = send(__fd, __buf + __off, __rem, __flags);
if (__snd > 0) {
__off += __snd;
__rem -= __snd;
}
else if (__snd == -1) {
perror("send:");
switch(errno) {
case EACCES: // not permission
break;
case EAGAIN: // The socket is marked nonblocking and the requested operation would block.
break;
case EALREADY: // Another Fast Open is in progress.
break;
case EBADF: // sockfd is not a valid open file descriptor.
break;
case ECONNRESET: // Connection reset by peer
break;
case EDESTADDRREQ: // The socket is not connection-mode, and no peer address is set.
break;
case EFAULT: // An invalid user space address was specified for an argument.:
break;
case EINTR: // A signal occurred before any data was transmitted;
break;
case EINVAL: // Invalid argument passed.
break;
case ENOBUFS: // The output queue for a network interface was full.
usleep(10000);
break;
case EPIPE: // The local end has been shut down on a connection oriented socket.
break;
default:
break;
}
}
}
return __off;
}
int main(int argc, char **argv) {
int ret;
int sockfd;
char buf[1024];
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1) {
handle_error("socket");
}
bzero(&addr, sizeof(addr));
addr.sin_port = htons(IBOX_PORT);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
if (ret == -1) {
close(sockfd);
handle_error("connect");
}
bzero(buf, sizeof(buf));
snprintf(buf, sizeof(buf), "[%d]: hello world\n", getpid());
ret = safe_send(sockfd, buf, sizeof(buf), 0);
if (ret > 0) {
//
}
usleep(100000);
bzero(buf, sizeof(buf));
snprintf(buf, sizeof(buf), "[%d]: byebye\n", getpid());
ret = safe_send(sockfd, buf, sizeof(buf), 0);
if (ret > 0) {
//
}
usleep(100000);
close(sockfd);
return 0;
}
Linux socket client
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 内部维护一个zookeeper集群,近期有用户反馈集群不稳定,导致业务侧有波动。根据用户提供的IP定位到异常并提供...
- https://riptutorial.com/cplusplus/example/24000/hello-tcp...
- 之前用的第三方的消息推送 jpush 的消息推送,和环信的Im。 目前个人觉得自己实现有两个简单的方案可以使用: ...
- 参考了这位作者的服务端配置:https://blog.csdn.net/qq_31967569/article/d...
- 第一种方式,使用基于Cocoa的第三方框架CocoaAsyncSocket 不需要升级握手协议,使用起来异常的简单...