TCP協議簡單實現聊天室 ubuntu 7.04

來源:互聯網
上載者:User

 

功能:群聊、私聊、儲存聊天記錄、檔案傳送

 

伺服器端函數:

1,

if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
  perror("socket");
  exit(1);
}

建立監聽通訊端

 

2,

ser_addr.sin_family = AF_INET;
 ser_addr.sin_port = htons(PORT);
 ser_addr.sin_addr.s_addr = INADDR_ANY;
 bzero(&(ser_addr.sin_zero), 8);

設定伺服器端參數

 

3,

if(bind(sock_fd, (struct sockaddr *)&ser_addr, sizeof(struct sockaddr)) < 0)
 {
  perror("bind");
  exit(1);
 }

綁定伺服器Ip、Port到通訊通訊端

 

4,

listen(sock_fd, MAX_QUE_CON_NUM);

監聽隊列裡的活動套解字

 

5,

select(MAX_SOCK_FD, &tem_inset, NULL, NULL, NULL)

調用select函數實現多工,伺服器可相應多用戶端

 

6,

accept(fd, (struct sockaddr *)&cli_addr, &sin_len)

調用accept 通過通訊通訊端fd接受用戶端相應

 

7,

recv(fd, buff, sizeof(buff), 0);

write(back_fd, buff, strlen(buff));

接收,發送資訊

 

8,

close(sock_fd)

關閉通訊端

 

用戶端函數

1,

if((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)

{

    exit(1);

}

建立通訊端

 

2,

connect(socket_fd, (struct sockaddr *)&ser_addr, sizeof(struct sockaddr)

串連到伺服器

 

3,

recv(sock_fd, buff, sizeof(buff);

send(sock_fd, buff, sizeof(buff), 0);

接收,發送資訊

 

4,

close(sock_fd)

關閉通訊端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.