#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>液穗
#include <ctype.h>
#define SERV_PORT 7000
//running command: "./server_tcp -p 7001"
int main(int argc, char** argv)
{
int opt
int port = SERV_PORT
while((opt = getopt(argc, argv, "p:")) != -1){
switch (opt){
case 'p': port = atoi(optarg)
break
default: break
}
}
struct sockaddr_in serv_addr, clnt_addr
socklen_t clnt_len
int lfd, cfd
int n, i
char buf[BUFSIZ]
lfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
if(lfd <0){
printf("%s\n", "socket error")
exit(1)
}
serv_addr.sin_family = AF_INET
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1")
serv_addr.sin_port = htons(port)
bind(lfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))
listen(lfd, 128)
clnt_len = sizeof(serv_addr)
cfd = accept(lfd, (struct sockaddr*)&clnt_addr, &clnt_len)
if(cfd == -1){
printf("accept error\n")
if(errno == EAGAIN || errno == EWOULDBLOCK){
printf("normal error"握埋宴)
}else{
printf("innormal error\n")
return -1
段银 }
}
while(1){
n = read(cfd, buf, BUFSIZ)
if(n >0){
printf("receive centent: %s\n", buf)
for(i = 0i <ni++){
buf[i] = toupper(buf[i])
}
}
write(cfd, buf, n)
}
close(cfd)
close(lfd)
return 0
}
客户端可以省略,使用nc命令可以模拟客户端连接: nc 127.1 7001
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main()
{
struct sockaddr_in serv_addr
int lfd
lfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
serv_addr.sin_family = AF_INET
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1")//服务器和客户端IP相同
serv_addr.sin_port = htons(6666)
connect(lfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))
write(lfd, "hello socket", strlen("hello socket"))
char rbuf[BUFSIZ]
read(lfd, rbuf, BUFSIZ)
printf("rbuf=%s\n", rbuf)
close(lfd)
return 0
}
代码如下:
while (1) {
// 这里不能用 绝芦serversoc, serversoc 是服务端监听套接字
// 要用 clientsoc
// 接收前可以先把 buf 清零
memset(buf, 0, sizeof(buf))
if (recv(clientsoc, buf, 1024, 0) <= 0) {
printf("读取失首返败!\n")
closesocket(clientsoc)
}
printf("接收来自者宏饥客户端的信息:%s\n", buf)
break
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)