套接字服务器-多线程 [英] Socket Server - Multithreaded

查看:66
本文介绍了套接字服务器-多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开套接字服务器,我有下面的代码,但是我的问题是,当我尝试 作为客户端使用命令行(telnet ip端口)连接到服务器,我只能输入1个字母,仅此而已,我无能为力,怎么办 我这样做是为了让客户可以发送任何东西,直到他们点击或键入EXIT?

I am trying to open a socket server, I have the code below but my problem is that when I try to  connect as a client to the server using the command line (telnet ip port), i only get to type 1 letter and that's it, i can't do anything else, how can I make it so that the client can send anything until they hit or type EXIT?

这是我的代码:

 

Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

Module Module1


  Sub Main()
    Dim serverSocket As New TcpListener(8888)
    Dim clientSocket As TcpClient
    Dim counter As Integer

    serverSocket.Start()
    msg("Server Started")
    counter = 0
    While (True)
      counter += 1
      clientSocket = serverSocket.AcceptTcpClient()
      msg("Client No:" + Convert.ToString(counter) + " started!")
      Dim client As New handleClient
      client.startClient(clientSocket, Convert.ToString(counter))
    End While

    clientSocket.Close()
    serverSocket.Stop()
    msg("exit")
    Console.ReadLine()
  End Sub

  Sub msg(ByVal mesg As String)
    mesg.Trim()
    Console.WriteLine(" >> " + mesg)
  End Sub

  Public Class handleClient
    Dim clientSocket As TcpClient
    Dim clNo As String
    Public Sub startClient(ByVal inClientSocket As TcpClient, _
    ByVal clineNo As String)
      Me.clientSocket = inClientSocket
      Me.clNo = clineNo
      Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
      ctThread.Start()
    End Sub
    Private Sub doChat()
      Dim requestCount As Integer
      Dim bytesFrom(10024) As Byte
      Dim dataFromClient As String
      Dim sendBytes As [Byte]()
      Dim serverResponse As String
      Dim rCount As String
      requestCount = 0

      While (True)
        Try
          requestCount = requestCount + 1
          Dim networkStream As NetworkStream = _
              clientSocket.GetStream()
          networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
          dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
          'dataFromClient = _
          'dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
          msg("From client-" + clNo + dataFromClient)
          rCount = Convert.ToString(requestCount)
          serverResponse = "Server to clinet(" + clNo + ") " + rCount
          sendBytes = Encoding.ASCII.GetBytes(serverResponse)
          networkStream.Write(sendBytes, 0, sendBytes.Length)
          networkStream.Flush()
          msg(serverResponse)
        Catch ex As Exception
          MsgBox(ex.ToString)
        End Try

      End While



    End Sub
  End Class



  'Sub Main()

  '  ' Must listen on correct port- must be same as port client wants to connect on.
  '  Const portNumber As Integer = 8000
  '  Dim tcpListener As New TcpListener(portNumber)
  '  tcpListener.Start()
  '  Console.WriteLine("Waiting for connection...")
  '  While (True)

  '    Try
  '      'Accept the pending client connection and return 
  '      'a TcpClient initialized for communication. 
  '      Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
  '      Console.WriteLine("Connection accepted.")
  '      ' Get the stream
  '      Dim networkStream As NetworkStream = tcpClient.GetStream()
  '      ' Read the stream into a byte array
  '      Dim bytes(tcpClient.ReceiveBufferSize) As Byte


  '      Dim clientdata As String = Encoding.ASCII.GetString(bytes)

  '      Do Until clientdata.Contains("exit")

  '        clientdata = Encoding.ASCII.GetString(bytes)

  '      Loop

  '      networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
  '      ' Return the data received from the client to the console.
  '      Console.WriteLine(("Client sent: " + clientdata))
  '      Dim responseString As String = "Message Received, thank you."
  '      Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
  '      networkStream.Write(sendBytes, 0, sendBytes.Length)
  '      Console.WriteLine(("Message Sent to> : " + responseString))
  '      'Any communication with the remote client using the TcpClient can go here.
  '      'Close TcpListener and TcpClient.
  '      tcpClient.Close()
  '      Console.WriteLine("exit")

  '    Catch e As Exception
  '      Console.WriteLine(e.ToString())
  '      Console.ReadLine()
  '    End Try

  '  End While

  '  tcpListener.Stop()
  '  Console.WriteLine("exit")
  '  Console.ReadLine()

  'End Sub

End Module

 

推荐答案

每个tcp连接基本上都是一个新线程,所以我会考虑将您的代码修改为如下所示,但是请记住,我很快就将其删除了,并且可能需要在此处和此处进行一些调整.

Each tcp connection is basically a new thread, so I would look at modifying you code to something like below, but remember I knocked this up quickly and it may need a tweak here and there..

 

Imports System.Net

Imports System.Net.Sockets

Imports System



Module Main



	Sub Main

	

	 ' start listening for new connections

  Dim listener As New TcpListener(IPAddress.Parse("127.0.0.1"), 8888)



  listener.Start()



  While True

   Dim User As New Client(listener.AcceptTcpClient)

    

  End While



End Module





Imports System.Net

Imports System.Net.Sockets



Public Class Client



 'used for sending/receiving data

 Private data() As Byte

 Private _CurrentClient As TcpClient



 Public Sub New(ByVal Client As TcpClient)

	

		_CurrentClient = Client

	

  ReDim data(_CurrentClient.ReceiveBufferSize)



  _CurrentClient.GetStream.BeginRead(data, 0, CInt(_CurrentClient.ReceiveBufferSize), AddressOf ReceiveMessage, Nothing)



 End Sub



	

 Public Sub ReceiveMessage(ByVal ar As IAsyncResult)

	

  'read from client

  Dim bytesRead As Integer



  Try

   SyncLock _CurrentClient.GetStream

    bytesRead = _CurrentClient.GetStream.EndRead(ar)

   End SyncLock



   'client has disconnected

   If bytesRead < 1 Then

    _CurrentClient.Close()

    Exit Sub

   Else

    'get the message sent

    Dim messageReceived As String = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead)



    Debug.WriteLine(messageReceived)



   End If





   'continue reading from client

   SyncLock _CurrentClient.GetStream

    _CurrentClient.GetStream.BeginRead(data, 0, CInt(_CurrentClient.ReceiveBufferSize), AddressOf ReceiveMessage, Nothing)

   End SyncLock



  Catch ex As Exception

   Debug.WriteLine("Error occurred: " & ex.Message & " Removing client")

   Try

    _CurrentClient.Close()

   Catch ex1 As Exception

    'ignore

   Finally

   End Try

  End Try



 End Sub

	



End Class


这篇关于套接字服务器-多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆