Socket套接字編程(一)——TCP編程

開始研究網絡編程,先從套接字編程開始,這個簡單,不過也得會才行。隨手寫點代碼先練練手,沒多少技術含量。

先熟悉下流程:

TCP型套接字:

<!-- /* Font Definitions */ @font-face {font-family:宋體; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋體"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋體; mso-font-kerning:1.0pt;} p {mso-margin-top-alt:auto; margin-right:0cm; mso-margin-bottom-alt:auto; margin-left:0cm; mso-pagination:widow-orphan; font-size:12.0pt; font-family:宋體; mso-bidi-font-family:宋體;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} -->

服務器端程序:
1
、加載套接字庫
2
、創建套接字(socket )。
3
、將套接字綁定到一個本地地址和端口上(bind )。
4
、將套接字設爲監聽模式,準備接收客戶請求(listen )。
5
、等待客戶請求到來;當請求到來後,接受連接請求,返回一個新的對應於此次連接的套接字(accept )。
6
、用返回的套接字和客戶端進行通信(send/recv )。
7
、返回,等待另一客戶請求。
8
、關閉套接字。
客戶端程序:
1
、加載套接字庫
2
、創建套接字(socket )。
3
、向服務器發出連接請求(connect )。
4
、和服務器端進行通信(send/recv )。
5
、關閉套接字。

 

下面直接上代碼:

服務器端代碼:

     客戶端代碼:

    

 

測試了一下沒多大問題,但也存在很多問題,什麼問題呢?下回分解

發佈了44 篇原創文章 · 獲贊 4 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章