//
// main.m
// DMTCPClient
//
// Created by 无痕 on 16/3/23.
// Copyright © 2016年 无痕. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>
void connectToServer();
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
connectToServer();
}
return 0;
}
#define MYPORT 9002
#define BUFFER_SIZE 1024
void connectToServer()
{
///定义sockfd
int sock_cli = socket(AF_INET,SOCK_STREAM, 0);
///定义sockaddr_in
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(MYPORT); ///服务器端口
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); ///服务器ip
///连接服务器,成功返回0,错误返回-1
if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("connect");
exit(1);
}
//
printf("连接服务器成功\n");
char sendbuf[BUFFER_SIZE];
char recvbuf[BUFFER_SIZE];
printf("等待输入中\n");
while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL)
{
printf("等待输入是否阻塞线程\n");
send(sock_cli, sendbuf, strlen(sendbuf),0); ///发送
printf("发送数据:%s\n", sendbuf);
if(strcmp(sendbuf,"exit\n")==0)
{
printf("发送退出信息\n");
break;
}
recv(sock_cli, recvbuf, sizeof(recvbuf),0); ///接收
printf("接收数据:%s\n", sendbuf);
// fputs(recvbuf, stdout);
memset(sendbuf, 0, sizeof(sendbuf));
memset(recvbuf, 0, sizeof(recvbuf));
}
close(sock_cli);
}