请问关于vb.net socket的连接问题

industrialit 2011-09-05 02:29:23
我这里有一个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

...全文
233 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
weiyiVB 2011-09-10
  • 打赏
  • 举报
回复
没有看明白,正在学习中
industrialit 2011-09-05
  • 打赏
  • 举报
回复
顶,任然没有解决问题
industrialit 2011-09-05
  • 打赏
  • 举报
回复
顶顶顶,任然没有发现问题
industrialit 2011-09-05
  • 打赏
  • 举报
回复
顶,代码很简单的,直接复制粘贴然后建两个textexboxt就ok
思考 2011-09-05
  • 打赏
  • 举报
回复
这么长?

1,502

社区成员

发帖
与我相关
我的任务
社区描述
VB 网络编程
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧