请问关于vb.net socket的连接问题
时间:2011-09-05
来源:互联网
我这里有一个server程序,还有一个client程序,程序代码如下,非常简单。我的问题是,如果我现在运行server,然后运行一个client,他们能顺利建立connection,然后如果我再运行一个client程序,这个client同样是connect到这个server的ip和port,然后我希望这个client程序能报错,因为我这个server不是多线程的,他的端口已经正在和一个client通信了,可是我运行了第二个client程序后,没有报错,是被socket的read方法block了,也就是表面上看去也和server程序连接上了,这就是我奇怪的地方,为什么一个端口能同时和不同的client的连上呢?不是一次只能建一个connection吗?请指教。
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
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
作者: industrialit 发布时间: 2011-09-05
这么长?
作者: bdxzq 发布时间: 2011-09-05
顶,代码很简单的,直接复制粘贴然后建两个textexboxt就ok
作者: industrialit 发布时间: 2011-09-05
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28