码迷,mamicode.com
首页 > 移动开发 > 详细

iOS socket TCP UDP

时间:2016-01-09 22:48:50      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

TCP:

服务器:

#import <Foundation/Foundation.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, const char * argv[])
{
    @autoreleasepool {
//        1
        int err;
        int fd=socket(AF_INET, SOCK_STREAM  , 0);
        BOOL success=(fd!=-1);
//        1
//   2     
        if (success) {
            NSLog(@"socket success");  
            struct sockaddr_in addr;
            memset(&addr, 0, sizeof(addr));
            addr.sin_len=sizeof(addr);
            addr.sin_family=AF_INET;
//            =======================================================================
            addr.sin_port=htons(1024);
//        ============================================================================
             addr.sin_addr.s_addr=INADDR_ANY;
            err=bind(fd, (const struct sockaddr *)&addr, sizeof(addr));
            success=(err==0);
        }
 //   2          
//        ============================================================================
        if (success) {
            NSLog(@"bind(绑定) success");
            err=listen(fd, 5);//开始监听
            success=(err==0);
        }
//    ============================================================================     
        //3
        if (success) {
            NSLog(@"listen success");
            while (true) {
                struct sockaddr_in peeraddr;
                int peerfd;
                socklen_t addrLen;
                addrLen=sizeof(peeraddr);
                NSLog(@"prepare accept");
                peerfd=accept(fd, (struct sockaddr *)&peeraddr, &addrLen);
                success=(peerfd!=-1);
//    ============================================================================
                if (success) {
                    NSLog(@"accept success,remote address:%s,port:%d",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port));
                    char buf[1024];
                    ssize_t count;
                    size_t len=sizeof(buf);
                    do {
                        count=recv(peerfd, buf, len, 0);
                        NSString* str = [NSString stringWithCString:buf encoding:NSUTF8StringEncoding];
                        NSLog(@"%@",str);
                    } while (strcmp(buf, "exit")!=0);
                }
//    ============================================================================
                close(peerfd);
            } 
        }  
//3     
    }
    return 0;
}

 

客户端:

//
//  main.m
//  kewai_SocketClient
//
#import <Foundation/Foundation.h>
#include <sys/socket.h>
#include <netinet/in.h>
#import <arpa/inet.h>
int main(int argc, const char * argv[])
{
    @autoreleasepool {
     //        1 
         int err;
        int fd=socket(AF_INET, SOCK_STREAM, 0);
        BOOL success=(fd!=-1);
        struct sockaddr_in addr;
     //        1
        //   2
        if (success) {
            NSLog(@"socket success");
            memset(&addr, 0, sizeof(addr));
            addr.sin_len=sizeof(addr);
            addr.sin_family=AF_INET;
            addr.sin_addr.s_addr=INADDR_ANY;
            err=bind(fd, (const struct sockaddr *)&addr, sizeof(addr));
            success=(err==0);
        }
        //   2
        //3
        if (success) {
//============================================================================           
            struct sockaddr_in peeraddr;
            memset(&peeraddr, 0, sizeof(peeraddr));
            peeraddr.sin_len=sizeof(peeraddr);
            peeraddr.sin_family=AF_INET;
            peeraddr.sin_port=htons(1024);
//            peeraddr.sin_addr.s_addr=INADDR_ANY;
            peeraddr.sin_addr.s_addr=inet_addr("172.16.10.120");
//            这个地址是服务器的地址, 
            socklen_t addrLen;
            addrLen =sizeof(peeraddr);
            NSLog(@"connecting");
            err=connect(fd, (struct sockaddr *)&peeraddr, addrLen);
            success=(err==0);
            if (success) {
//                struct sockaddr_in addr;
                err =getsockname(fd, (struct sockaddr *)&addr, &addrLen);
                success=(err==0);
//============================================================================
//============================================================================
                if (success) {
                      NSLog(@"connect success,local address:%s,port:%d",inet_ntoa(addr.sin_addr),ntohs(addr.sin_port));
                    char buf[1024];
                    do {
                        printf("input message:");
                        scanf("%s",buf);
                        send(fd, buf, 1024, 0);
                    } while (strcmp(buf, "exit")!=0); 
                }
            }
            else{
                NSLog(@"connect failed");
            }
        }
    //    ============================================================================
        //3
    }
    return 0;
}

 

 

UDP:

 

服务器:

/*
 *UDP/IP应用编程接口(API)
 *服务器的工作流程:首先调用socket函数创建一个Socket,然后调用bind函数将其与本机
 *地址以及一个本地端口号绑定,接收到一个客户端时,服务器显示该客户端的IP地址,并将字串
 *返回给客户端。
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#import <arpa/inet.h>
int main(int argc,char **argv)
{
    int ser_sockfd;
    int len;
    //int addrlen;
    socklen_t addrlen;
    char seraddr[100];
    struct sockaddr_in ser_addr;
    /*建立socket*/
    ser_sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(ser_sockfd<0)
    { 
        printf("I cannot socket success\n");
        return 1;
    }
    /*填写sockaddr_in 结构*/
    addrlen=sizeof(struct sockaddr_in);
    bzero(&ser_addr,addrlen);
    ser_addr.sin_family=AF_INET;
    ser_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    ser_addr.sin_port=htons(1024);
    /*绑定客户端*/
    if(bind(ser_sockfd,(struct sockaddr *)&ser_addr,addrlen)<0)
    {
        printf("connect");
        return 1;
    }
    while(1)
    {
        bzero(seraddr,sizeof(seraddr));
        len=recvfrom(ser_sockfd,seraddr,sizeof(seraddr),0,(struct sockaddr*)&ser_addr,&addrlen);
        /*显示client端的网络地址*/
        printf("receive from %s\n",inet_ntoa(ser_addr.sin_addr));
        /*显示客户端发来的字串*/ 
        printf("recevce:%s",seraddr);
        /*将字串返回给client端*/
        sendto(ser_sockfd,seraddr,len,0,(struct sockaddr*)&ser_addr,addrlen);
    }
}

 

 

客户端:

/*
 *UDP/IP应用编程接口(API)
 *客户端的工作流程:首先调用socket函数创建一个Socket,填写服务器地址及端口号,
 *从标准输入设备中取得字符串,将字符串传送给服务器端,并接收服务器端返回的字
 *符串。最后关闭该socket。
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <netinet/in.h>
#import <arpa/inet.h>
int GetServerAddr(char * addrname)
{
    printf("please input server addr:");
    scanf("%s",addrname);
    return 1; 
}
int main(int argc,char **argv)
{
    int cli_sockfd;
    int len;
    socklen_t addrlen;
    char seraddr[14];
    struct sockaddr_in cli_addr;
    char buffer[256];
    GetServerAddr(seraddr);
    /* 建立socket*/
    cli_sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(cli_sockfd<0)   
    {  
        printf("I cannot socket success\n"); 
        return 1; 
    }
    /* 填写sockaddr_in*/
    addrlen=sizeof(struct sockaddr_in);
    bzero(&cli_addr,addrlen);
    cli_addr.sin_family=AF_INET;
    cli_addr.sin_addr.s_addr=inet_addr(seraddr);
    //cli_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    cli_addr.sin_port=htons(1024);
    bzero(buffer,sizeof(buffer));
    /* 从标准输入设备取得字符串*/
    len=read(STDIN_FILENO,buffer,sizeof(buffer));
    /* 将字符串传送给server端*/
    sendto(cli_sockfd,buffer,len,0,(struct sockaddr*)&cli_addr,addrlen);
    /* 接收server端返回的字符串*/
    len=recvfrom(cli_sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&cli_addr,&addrlen);
    //printf("receive from %s\n",inet_ntoa(cli_addr.sin_addr));
    printf("receive: %s",buffer);
    close(cli_sockfd); 
}

 

iOS socket TCP UDP

标签:

原文地址:http://www.cnblogs.com/ficow/p/5117358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!