BSD Socket~TCP~Example Code

TCP 协议实现 C版本,可用于Mac OS X机器上运行

Server:

/*
Setting up a simple TCP server involves the following steps:

Creating a TCP socket, with a call to socket().
Binding the socket to the listen port, with a call to bind(). Before calling bind(), a programmer must declare a sockaddr_in structure, clear it (with memset()), and the sin_family (AF_INET), and fill its sin_port (the listening port, in network byte order) fields. Converting a short int to network byte order can be done by calling the function htons() (host to network short).
Preparing the socket to listen for connections (making it a listening socket), with a call to listen().
Accepting incoming connections, via a call to accept(). This blocks until an incoming connection is received, and then returns a socket descriptor for the accepted connection. The initial descriptor remains a listening descriptor, and accept() can be called again at any time with this socket, until it is closed.
Communicating with the remote host, which can be done through send() and recv() or write() and read().
Eventually closing each socket that was opened, once it is no longer needed, using close().
Code may set up a TCP server on port 1100 as follows:
*/

/* Server code in C */

  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>

  int main(void)
  {
    struct sockaddr_in stSockAddr;
    int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    if(-1 == SocketFD)
    {
      perror("can not create socket");
      exit(EXIT_FAILURE);
    }

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

    stSockAddr.sin_family = AF_INET;
    stSockAddr.sin_port = htons(1100);
    stSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(-1 == bind(SocketFD,(struct sockaddr *)&stSockAddr, sizeof(stSockAddr)))
    {
      perror("error bind failed");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }

    if(-1 == listen(SocketFD, 10))
    {
      perror("error listen failed");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }

    for(;;)
    {
      int ConnectFD = accept(SocketFD, NULL, NULL);

      if(0 > ConnectFD)
      {
        perror("error accept failed");
        close(SocketFD);
        exit(EXIT_FAILURE);
      }

      /* perform read write operations ...
      read(ConnectFD,buff,size)*/

      if (-1 == shutdown(ConnectFD, SHUT_RDWR))
      {
        perror("can not shutdown socket");
        close(ConnectFD);
        close(SocketFD);
        exit(EXIT_FAILURE);
      }
      close(ConnectFD);
    }

    close(SocketFD);
    return EXIT_SUCCESS;
}

Client

/*
Programming a TCP client application involves the following steps:

Creating a TCP socket, with a call to socket().
Connecting to the server with the use of connect(), passing a sockaddr_in structure with the sin_family set to AF_INET, sin_port set to the port the endpoint is listening (in network byte order), and sin_addr set to the IP address of the listening server (also in network byte order.)
Communicating with the server by using send() and recv() or write() and read().
Terminating the connection and cleaning up with a call to close().
*/

  /* Client code in C */

  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>

  int main(void)
  {
    struct sockaddr_in stSockAddr;
    int Res;
    int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (-1 == SocketFD)
    {
      perror("cannot create socket");
      exit(EXIT_FAILURE);
    }

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

    stSockAddr.sin_family = AF_INET;
    stSockAddr.sin_port = htons(1100);
    Res = inet_pton(AF_INET, "192.168.1.3", &stSockAddr.sin_addr);

    if (0 > Res)
    {
      perror("error: first parameter is not a valid address family");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }
    else if (0 == Res)
    {
      perror("char string (second parameter does not contain valid ipaddress)");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }

    if (-1 == connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof(stSockAddr)))
    {
      perror("connect failed");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }

    /* perform read write operations ... */

    (void) shutdown(SocketFD, SHUT_RDWR);

    close(SocketFD);
    return EXIT_SUCCESS;
  }

Link:

BSD Socket  Wikipedia

BSD Socket~TCP~Example Code

时间: 2024-10-08 13:30:40

BSD Socket~TCP~Example Code的相关文章

BSD Socket~UDP~Code examples

C 代码,可以用于OSX运行 /* Client-server example using UDP[edit] The User Datagram Protocol (UDP) is a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. Because of this minimal design, U

BSD socket API

伯克利套接字(Berkeley sockets),也称为BSD Socket.伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信. BSD Socket的应用编程接口已经是网络套接字的抽象标准.大多数其他程序语言使用一种相似的编程接口.它最初是由加州伯克利大学为Unix系统开发出来的.所有现代的操作系统都实现了伯克利套接字接口,因为它已经是连接互联网的标准接口了. API函数 这些是伯克利套接字提供的库函数. socket() 创造某种类型的套接字,分配

Socket &amp; TCP &amp;HTTP

1.TCP协议的三次握手和四次挥手2.SOCKET连接与TCP连接3.SOCKET详解 3.1 socket套接字的起源 3.2 套接字描述符 3.3. SOCKET连接的程序 4.TCP/IP.Http,Socket关系研究,TCP和UDP的区别 1.TCP协议的三次握手和四次挥手 TCP协议的三次握手和四次挥手是很经典的内容 内容来源于 http://blog.csdn.net/whuslei/article/details/6667471 http://blog.csdn.net/zeng

socket tcp缓冲区大小的默认值、最大值

Author:阿冬哥 Created:2013-4-17 Blog:http://blog.csdn.net/c359719435/ Copyright 2013 阿冬哥 http://blog.csdn.net/c359719435/ 使用以及转载请注明出处 1 设置socket tcp缓冲区大小的疑惑 疑惑1:通过setsockopt设置SO_SNDBUF.SO_RCVBUF这连个默认缓冲区的值,再用getsockopt获取设置的值,发现返回值是设置值的两倍.为什么? 通过网上查找,看到li

unp第七章补充之socket tcp 产生 rst响应的情况

socket tcp 产生 rst响应的情况(属于硬错误) 1.     syn发送到服务器主机,但是目的端口并未运行.则产生一个ECONRFUSED错误.客户端立即返回.比如telnet 192.168.1.55 8889,条件:55主机在局域网上并且可达(也可以换成可以到达的网络ip地址),但是8889这个端口并未使用(可能服务器已经关闭),则服务器(对方主机tcp内核)发送一个rst相应给客户端,于是客户端立即关闭. 注意一下,如果输入的网络ip不可达的话,客户端将会持续发送syn,最后产

关于socket tcp 断线重连

这个问题困扰过我几次,都没有来得及研究,今天研究一下. 首先写一个最简易的socket tcp程序,连接成功后再关闭服务器然后再用客户端各种操作看是什么情况 测试表明 (1)客户端已经连接,当服务端关闭程序时,客户端调用send函数发送失败,WSAGetLastError() 返回10054(远程主机强迫关闭了一个现有的连接) (2)客户端已经连接,当客户端关闭程序时,服务端调用recv函数接收失败,WSAGetLastError() 返回10054(远程主机强迫关闭了一个现有的连接) ,这时对

c#异步Socket Tcp服务器实现

原创性申明 本文作者: 小竹zz  本文地址:http://blog.csdn.net/zhujunxxxxx 转载请注明出处. 介绍 我之前写过一篇IOCP的文章: http://blog.csdn.net/zhujunxxxxx/article/details/43573879 这个比异步socket性能好,因为它复用对象了. 在c#中微软已经提供了TcpListener和TcpClient来实现Tcp的通讯,这部分已经有人写了比较好的异步服务器代码 http://www.cnblogs.c

SOCKET TCP 粘包及半包问题

大家在使用SOCKET通信编程的时候,一般会采用UDP和TCP两种方式:TCP因为它没有包的概念,它只有流的概念,并且因为发送或接收缓冲区大小的设置问题,会产生粘包及半包的现象. 场景: 服务端向连续发送三个"HelloWorld"(三次消息无间隔),那么客户端接收到的情况会有以下三种: 1)HelloWorld HelloWorld HelloWorld (客户端接收三次) 2)HelloWorldHelloWor ldHelloWorld (客户端接收两次) 3)HelloWorl

Photon服务器引擎(二)socket/TCP/UDP基础及Unity聊天室的实现

Photon服务器引擎(二)socket/TCP/UDP基础及Unity聊天室的实现 我们平时说的最多的socket是什么呢,实际上socket是对TCP/IP协议的封装,Socket本身并不是协议,而是一个调用接口(API). 通过Socket,我们才能使用TCP/IP协议.实际上,Socket跟TCP/IP协议没有必然的联系.Socket编程接口在设计的时候,就希望也能适应其他的网络协议.所以说,Socket的出现只是使得程序员更方便地使用TCP/IP协议栈而已,是对TCP/IP协议的抽象,