程式設計工藝大師許志宇老師:http://tccnchsu.blogspot.com/
TCP和UDP的差異
在 TCP/ IP 協定家族中﹐傳送層主要有兩個協定﹕TCP 與 UDP。究竟兩者有何不同呢﹖簡單而言﹐TCP 提供的是一個連線導向(Connection Oriented)的可靠傳輸﹐前面所介紹的傳送層檢測手續﹐都會在 TCP 中得到實現。相對而言﹐UDP 則是一個非連線型(Connectionless)的非可靠傳輸協定﹐它並不會運用確認機制來保證資料是否正確的被接收、不需要重傳遺失的資料、資料的接收可不必按順序進行、也不提供回傳機制來控制資料流的速度。因此﹐ UDP 信息可能會在網路傳送過程中丟失﹑重複﹑或不依順序﹐而且抵達速度也可能比接收端的處理速度還快。對於某些訊息量較大、時效性大於可靠性的傳輸來說(比方說語音 / 影像),UDP 的確是個不錯的選擇。
(資料來源:
http://www.pcnet.idv.tw/pcnet/network/network_ip_tcp.htm)
TCP與UDP的程式差異:
socket()參數不同
UDP Server不需要使用listen及accept
UDP收發資料用sendto/recvfrom
TCP:address message在connect/accept時決定
UDP:在每次的sendto/recvfrom函式中取得address message
UDP:shutdown無效
(資料來源:
http://blog.yam.com/ibma92157/article/27580746)
========================================================================client
Private Sub cmdConnect_Click()
Winsock1.LocalPort = 6666 '以便自動產生Local Port
Winsock1.Connect "192.168.x.x" '設定改成您 Server 電腦的IP 號碼
End Sub
Private Sub cmdExit_Click()
Winsock1.SendData "close"
DoEvents
Winsock1.Close
Winsock1.LocalPort = 0
End Sub
Private Sub cmdSend_Click()
Winsock1.SendData txtOutput.Text
DoEvents
End Sub
Private Sub Form_Load()
Winsock1.RemotePort = 7777 '設定與Server端做Listen的Port相同
End Sub
Private Sub Form_Unload(Cancel As Integer)
If Winsock1.State <> sckClosed Then
cmdExit_Click
End If
End Sub
Private Sub Winsock1_Connect()
If Winsock1.State = sckConnected Then
lstInput.AddItem "Connected! LocalPort =" & Winsock1.LocalPort _
& " RemptePort = " & Winsock1.RemotePort
End If
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim mydata As String
Winsock1.GetData mydata, vbString
lstInput.AddItem mydata
End Sub
Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
lstInput.AddItem Description
End Sub
========================================================================
server
Private Sub cmdSend_Click()
Winsock1.SendData txtSend.Text
End Sub
Private Sub Form_Load()
Winsock1.LocalPort = 7777
Winsock1.Listen '監聽
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
Winsock1.GetData strData, vbString
txtReceived.Text = strData
If strData = "close" Then
Winsock1.Close
cmdSend.Enabled = False
Winsock1.Listen
End If
End Sub
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
MsgBox "有人敲門"
Winsock1.Close
Winsock1.Accept requestID '改成接受
cmdSend.Enabled = True
End Sub
=======================================================================