none
用form製作測試連結socket的程式 連不到?? RRS feed

  • 問題

  • 這是原始碼

    form1.vb

    Code Snippet

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

    Public Class Form1

      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
          Dim serverSocket As New Socket( _
            AddressFamily.InterNetwork, _
            SocketType.Stream, _
            ProtocolType.Tcp)
                Dim serverIP As IPAddress = IPAddress.Parse("127.0.0.1")
          ' Dim serverIP As IPAddress = Dns.Resolve("localhost").AddressList(0)

          ' Port = 80
          Dim Port As String = "80"
          Dim serverhost As New IPEndPoint(serverIP, Int32.Parse(Port))

          serverSocket.Bind(serverhost)

          ' Backlog = 50
          serverSocket.Listen(50)

          ListBox1.Items.Clear()

          ListBox1.Items.Add("Server started at: " + serverIP.ToString() + ":" + Port)

          Dim lc As New ListenClient(serverSocket)
          lc.MainForm = Me

          Dim serverthread As Threading.Thread

          serverthread = New Thread( _
              New Threading.ThreadStart(AddressOf lc.ServerThreadProc))

          serverthread.Start()

        Catch ex As Exception
          ListBox1.Items.Add(ex.StackTrace.ToString())
        End Try
      End Sub
    End Class

     

    listenclient

    Code Snippet

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

    Public Class ListenClient
      Private serverSocket As System.Net.Sockets.Socket
      Private clientSocket As System.Net.Sockets.Socket

      Friend MainForm As Form1

      ' 建構函式
      Public Sub New(ByVal serverSocket As System.Net.Sockets.Socket)
        Me.serverSocket = serverSocket
      End Sub

      Public Sub ServerThreadProc()
        Do While True
          Try
            Dim clientSocket As Socket = serverSocket.Accept()

            Dim clientInfo As IPEndPoint = CType( _
                clientSocket.RemoteEndPoint, _
                IPEndPoint)
            Dim serverInfo As IPEndPoint = CType( _
                serverSocket.LocalEndPoint, _
                IPEndPoint)

            MainForm.ListBox1.Items.Add("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString())
            MainForm.ListBox1.Items.Add("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString())
          Catch ex As Exception
            Console.WriteLine(ex.StackTrace.ToString())
          End Try
        Loop
      End Sub
    End Class

     

     我按F5測試

    用ie打上http://127.0.0.1

    沒回應= =

    感覺是執行緒的問題....

    該怎麼修改呢?

    PS我說不清楚可以跟我說喔

     

     

    2007年7月25日 下午 01:02

解答

  • HI,

     

    基本上IE是使用HTTP協定和WEB伺服器溝通, 而您的程式卻是接受使用TCP協定的用戶端, 所以您應該寫一個使用TCP協定的用戶端, 再呼叫Connect方法連線到您的Server程式

     

    tihs

    2007年7月27日 上午 01:48