请问关于vb.net socket的连接问题
server代码:
Public Class Server
Inherits Form
' TextBoxes for receiving user input and displaying information
Private connection As Socket ' Socket object handles connection
Private readThread As Thread ' server thread
'Friend WithEvents txtInput As TextBox
'Friend WithEvents txtInput As TextBox
' Stream through which to transfer data
Private socketStream As NetworkStream
' objects for writing and reading data
Private writer As BinaryWriter
Private reader As BinaryReader
Dim counter As Integer = 1
Public Sub New()
MyBase.New()
' equired by the Windows Form Designer.
InitializeComponent()
' Server portion of a client/server stream-socket connection (part 1 of 4)
' add any initialization after the
' InitializeComponent call
' create thread from server
Control.CheckForIllegalCrossThreadCalls = False
readThread = New Thread(AddressOf RunServer)
readThread.Start()
End Sub ' New
' Visual Studio .NET generated code
' invoked when user closes server
Private Sub FrmServer_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
System.Environment.Exit(System.Environment.ExitCode)
End Sub ' FrmServer_Closing
' send server text to client
Private Sub txtInput_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtInput.KeyDown
' send text to client
Try
' send text if user pressed Enter and connection exists
If (e.KeyCode = Keys.Enter AndAlso Not connection Is Nothing) Then
writer.Write("SERVER>>> " & txtInput.Text) ' send data
StatusTxtBx.Text &= vbCrLf & "SERVER>>> " & _
txtInput.Text
' close connection if server’s user signals termination
If txtInput.Text = "TERMINATE" Then
connection.Close()
End If
txtInput.Clear()
End If
' handle exception if error occurs when server sends data
Catch exception As SocketException
StatusTxtBx.Text &= vbCrLf & "Error writing object"
End Try
End Sub ' txtInput_KeyDown
' allow client to connect and display text sent by user
Public Sub RunServer()
Dim listener As TcpListener
' wait for request, then establish connection
Try
' Step 1: create TcpListener
listener = New TcpListener(5000)
listener.ExclusiveAddressUse = True
' Step 2: TcpListener waits for connection request
listener.Start()
' Step 3: establish connection upon client request
While True
StatusTxtBx.Text = "Waiting for connection" & vbCrLf
' accept an incoming connection
connection = listener.AcceptSocket()
' create NetworkStream object associated with socket
socketStream = New NetworkStream(connection)
' create objects for transferring data across stream
writer = New BinaryWriter(socketStream)
reader = New BinaryReader(socketStream)
StatusTxtBx.Text &= "Connection " & counter & _
" received." & vbCrLf
' inform client that connection was successfull
writer.Write("SERVER>>> Connection successful")
txtInput.ReadOnly = False
Dim theReply As String = ""
' Step 4: read String data sent from client
Try
' loop until client signals termination
Do
theReply = reader.ReadString() ' read data
' display message
StatusTxtBx.Text &= vbCrLf & theReply
Loop While (theReply <> "CLIENT>>> TERMINATE" _
AndAlso connection.Connected)
' handle exception if error reading data
Catch inputOutputException As IOException
MessageBox.Show("Client application closing")
' close connections
Finally
StatusTxtBx.Text &= vbCrLf & _
"User terminated connection"
txtInput.ReadOnly = True
' Step 5: close connection
writer.Close()
reader.Close()
socketStream.Close()
connection.Close()
counter += 1
End Try
End While
' handle exception if error occurs in establishing connection
Catch inputOutputException As IOException
MessageBox.Show("Server application closing")
End Try
End Sub ' RunServer
End Class ' FrmServer
client代码:
Public Class Client
Inherits Form
' TextBoxes for inputting and displaying information
'Friend WithEvents txtInput As TextBox
'Friend WithEvents txtDisplay As TextBox
' stream for sending data to server
Private output As NetworkStream
' objects for writing and reading bytes to streams
Private writer As BinaryWriter
Private reader As BinaryReader
Private message As String = "" ' message sent to server
' thread prevents client from blocking data transfer
Private readThread As Thread
Public Sub New()
MyBase.New()
' equired by the Windows Form Designer.
InitializeComponent()
Control.CheckForIllegalCrossThreadCalls = False
' add any initialization after the
' InitializeComponent call
readThread = New Thread(AddressOf RunClient)
readThread.Start()
End Sub ' New
' Visual Studio .NET generated code
' invoked when user closes application
Private Sub FrmClient_Closing(ByVal sender As System.Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing
System.Environment.Exit(System.Environment.ExitCode)
End Sub
' send user input to server
Private Sub txtInput_KeyDown(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles txtInput.KeyDown
' send user input if user pressed Enter
Try
' determine whether user pressed Enter
If e.KeyCode = Keys.Enter Then
' send data to server
writer.Write("CLIENT>>> " & txtInput.Text)
txtDisplay.Text &= vbCrLf & "CLIENT>>> " & _
txtInput.Text
txtInput.Clear()
End If
' handle exception if error occurs in sending data to server
Catch exception As SocketException
txtDisplay.Text &= vbCrLf & "Error writing object"
End Try
End Sub ' txtInput_KeyDown
' connect to server and display server-generated text
Public Sub RunClient()
Dim client As TcpClient
' instantiate TcpClient for sending data to server
Try
txtDisplay.Text &= "Attempting connection" & vbCrLf
' Step 1: create TcpClient and connect to server
client = New TcpClient()
client.Connect("127.0.0.1", 5000)
client.SendTimeout = 1
' Step 2: get NetworkStream associated with TcpClient
output = client.GetStream()
' create objects for writing and reading across stream
writer = New BinaryWriter(output)
reader = New BinaryReader(output)
txtDisplay.Text &= vbCrLf & "Got I/O streams" & vbCrLf
txtInput.ReadOnly = False
' Step 3: processing phase
Try
' loop until server signals termination
Do
' read message from server
message = reader.ReadString
txtDisplay.Text &= vbCrLf & message
Loop While message <> "SERVER>>> TERMINATE"
' handle exception if error in reading server data
: Catch inputOutputException As IOException
MessageBox.Show("Client application closing")
' Step 4: close connection
Finally
txtDisplay.Text &= vbCrLf & "Closing connection." & vbCrLf
writer.Close()
reader.Close()
output.Close()
client.Close()
End Try
Application.Exit()
' handle exception if error in establishing connection
Catch inputOutputException As Exception
MessageBox.Show("Client application closing")
End Try
End Sub ' RunClient
End Class ' FrmClient
相关推荐
经典 VB.net 里面的socket通讯范例
这是一个经典的 VB.net通讯范例 主要需要在服务器里开启端口 详细见帖子: https://bbs.csdn.net/topics/new?forum_id=VBDotNET
VB.NET Socket聊天室实战:服务端、心跳检测与消息广播
网络编程是构建分布式应用的基础,而TCP Socket作为最经典的长连接技术,广泛应用于即时通讯、设备监控等场景。其核心原理是通过套接字建立可靠的双向字节流,但开发者需解决粘包拆包、连接状态维护等关键问题。心跳检测机制通过周期性发送探测消息,能有效识别半开连接,保障服务端资源不被僵尸链接占用,是生产级系统的必备设计。在工业控制、内部协作等中小规模应用中,利用VB.NET的System.Net.Sockets命名空间可快速实现多人在线聊天室。本文从TCP服务端异步监听、消息广播、客户端收发,到心跳超时清理全流
基于VB.NET的Socket多人聊天室:心跳检测与死连接清理实践
在网络编程中,基于TCP的Socket编程是构建实时通信应用的基础。虽然TCP长连接能保证数据传输的可靠性,但它无法主动感知对端是否已经崩溃或断网,这导致死连接占用资源、消息发送失败等问题。心跳检测机制应运而生——通过客户端定期发送心跳包,服务端据此判断连接存活状态,并及时清理超时连接。这种技术广泛用于即时通讯、多人聊天室、IoT设备管理等场景。本文基于VB.NET完整实现了一个多人聊天室系统,涵盖了服务端监听、消息广播、用户管理以及心跳检测等核心环节,并针对死连接堆积、端口占用、粘包半包等高频问题给出了实
VB.NET SOCKET编程
应用vb2008开发的实现一服务对多客户端的源码程序,对网络编程非常实用.
VB.NET2008运用Socket 解决DDE通信
vb6移植到vb2008的时候必须解决的DDE通信问题,本人做了个测试例子,希望大街指点下。这个程序中有VB6的也用。net的桌面程序。


网络编程
