您的位置:首页 > 理论基础 > 计算机网络

Tcpsocket

2016-03-14 16:11 351 查看
qt服务器:

#include <QCoreApplication>

#include <stdlib.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <unistd.h>

#include <QDebug>

#define PORT 3880

int main(int argc, char *argv[])

{

    QCoreApplication a(argc, argv);

    int listenfd;

    int confd;

    int n;

    char buf[100];

    socklen_t clientInfo;  // socket len

    struct sockaddr_in cliaddr,serverAddr;

    qDebug()<<"创建socket套接字"<<endl;

    listenfd = socket(AF_INET,SOCK_STREAM,0);

    serverAddr.sin_family = AF_INET;

    serverAddr.sin_addr.s_addr= htonl(INADDR_ANY);

    serverAddr.sin_port=htons(PORT);

    qDebug()<<" connection。。。。"<<endl;

    bind(listenfd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));

    listen(listenfd,8);

    while(true)

    {

        clientInfo = sizeof(cliaddr);

        confd = accept(listenfd,(struct sockaddr*)&cliaddr,&clientInfo);

        if ((n = recv(confd,buf,100,0))>0)

        {

            qDebug()<<"recevie data is:"<<buf<<endl;

        }

        qDebug()<<"socket information:"<<confd<<endl;

        qDebug()<<"client ip:"<<cliaddr.sin_addr.s_addr<<endl;

        if(!fork())

        {

            close(listenfd);

             while((n = recv(confd,buf,100,0))>0)

             {

                 puts(buf);

             }

        }

//        close(confd);

//        exit(0);

    }

    close(listenfd);

    return a.exec();

}

ios客户端:

#import "ViewController.h"

#include <sys/socket.h>

#include <netinet/in.h>

#include <unistd.h>

#include <arpa/inet.h>

#define PORT 3880;

@interface
ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super
viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning {

    [super
didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(IBAction)click:(id)sender

{

    NSLog(@"connection server");

    struct sockaddr_in seraddr;

    char sendLine[100] =
"HELLO WORLD";

    

    int sockfd = socket(AF_INET,
SOCK_STREAM, 0);

    if(sockfd <0)

    {

        int temp =
errno;

        NSLog(@"%d",errno);

    }

    memset(&seraddr,
0, sizeof(seraddr));

    seraddr.sin_family =
AF_INET;

    seraddr.sin_addr.s_addr =
inet_addr("192.168.3.166");

    seraddr.sin_port =
htons(3880);

    

    int fd;

    int conInfo =
connect(sockfd, (struct
sockaddr*)&seraddr, sizeof(seraddr));

    if(conInfo<0)

        NSLog(@"connection information error: ");

//    while (fgets(sendLine, 100, stdin) != NULL) {

//        send(fd,sendLine,strlen(sendLine),0);

//    }

     send(fd,sendLine,strlen(sendLine),0);

    

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: