当前位置:编程学习 > C#/ASP.NET >>

vb.net怎样实现多客户端与服务器端通信

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

Public Class UsingAsyncSocketServer
    Dim strMessage As String
    Dim myListener As Socket
    Dim bteAccept(65536) As Byte
    Dim bteSend(65536) As Byte
    Dim EndSocket As Socket
    Dim myThread1 As Thread

    Private Sub 开始监听Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 开始监听Button.Click
        myThread1 = New Thread(New ThreadStart(AddressOf StartListen))
        myThread1.Start()
    End Sub

    Private Sub 发送Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 发送Button.Click
        Dim myThread As New Thread(New ThreadStart(AddressOf SendStart))
        myThread.Start()
    End Sub

    Private Sub StartListen()
        Dim intPort As Integer
        Dim bidEndPoint As IPEndPoint

        intPort = Integer.Parse(Me.通信端口TextBox.Text)
        bidEndPoint = New IPEndPoint(IPAddress.Parse("10.111.1.36"), intPort)
        myListener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Try
            myListener.Bind(bidEndPoint)
            Dim myAsyncCallback As New AsyncCallback(AddressOf AcceptEnd)
            myListener.Listen(100)
            myListener.BeginAccept(myAsyncCallback, myListener)
            Me.联机信息RichTextBox.Text = "等待联机中,开始整理数据......"
        Catch ex As Exception
            MessageBox.Show(ex.Message, "打开连接错误", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Private Sub AcceptEnd(ByVal pIAsyncResult As IAsyncResult)
        EndSocket = myListener.EndAccept(pIAsyncResult)
        Me.联机信息RichTextBox.Text += vbCrLf & "已接受客户端联机请求!"
        Dim myAsyncCallback As New AsyncCallback(AddressOf ReceiveData)

        EndSocket.BeginReceive(bteAccept, 0, 65536, SocketFlags.None, myAsyncCallback, EndSocket)
        Me.联机信息RichTextBox.Text += vbCrLf & "开始接收客户端传送的数据内容......"
    End Sub

    Private Sub ReceiveData(ByVal pIAsyncResult As IAsyncResult)
        Dim intByte As Integer
        intByte = EndSocket.EndReceive(pIAsyncResult)
        If intByte > 0 Then
            Me.接收数据RichTextBox.Text += Encoding.Default.GetString(bteAccept)
        End If
        Me.联机信息RichTextBox.Text += vbCrLf & "成功接收客户端所传送的数据内容! " & intByte.ToString & " 个字节"
        Array.Clear(bteAccept, 0, bteAccept.Length)
        Dim myAsyncCallback As New AsyncCallback(AddressOf ReceiveData)

        EndSocket.BeginReceive(bteAccept, 0, 65536, SocketFlags.None, myAsyncCallback, EndSocket)
    End Sub

    Private Sub SendStart()
        Dim myAsyncCallback As New AsyncCallback(AddressOf SendData)
        bteSend = Encoding.Default.GetBytes(Me.发送数据RichTextBox.Text)

        EndSocket.BeginSend(bteSend, 0, bteSend.Length, SocketFlags.DontRoute, myAsyncCallback, EndSocket)
        Me.联机信息RichTextBox.Text += vbCrLf & "开始传送数据至客户端......"
    End Sub

    Private Sub SendData(ByVal pIAsyncResult As IAsyncResult)
        Dim intSend As Integer
        intSend = EndSocket.EndSend(pIAsyncResult)
        Me.联机信息RichTextBox.Text += vbCrLf & "数据传送完成,总共传送 " & intSend.ToString & " 个字节!"
    End Sub

    Private Sub 停止联机Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 停止联机Button.Click
        myListener.Close()
        myThread1.Abort()
        MessageBox.Show("结束联机操作!", "停止监听", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub UsingAsyncSocketServer_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
    End Sub
End Class


这是服务器端代码,怎么修改成多客户端的服务器端代码,万分感谢! --------------------编程问答--------------------  VB.Net程序设计:简单的通信系统-远程控制+聊天功能
http://blog.csdn.net/linjimu/article/details/4092698
里面实现了一个服务端,多个客服端的功能。 --------------------编程问答-------------------- 没有看到这个程序的代码呀,怎么下载呀,急呀...... --------------------编程问答-------------------- 用线程来实现啊。 --------------------编程问答--------------------
Public Class ClientOrder''通过属性来进行外部访问
    Private ClientID As Integer
    Public Property ID() As Integer
        Get
            Return ClientID
        End Get
        Set(ByVal value As Integer)
            ClientID = value
        End Set
    End Property
End Class

Public Class ClientOrder''直接访问
Public ClientID as Integer=0
End class


1.这个两种访问的区别在哪?
2.对程序的影响有哪些,采用哪种较好
3.在对这个类进行实例的时候,必须用New?为什么直接访问的时候不用new也可以?
--------------------编程问答-------------------- 我知道用线程,但是不会用线程呀。还有就是是用线程好呢,还是线程池好呢。我这个就需要两个客户端就行了。请高手给指指,改改。跪谢 --------------------编程问答-------------------- 如果有高手帮忙的话,分还可以继续加...... --------------------编程问答-------------------- 具体点儿,能够实现多客户端的话,分还可以加..... --------------------编程问答-------------------- 代码以前写的。
很差劲的。 --------------------编程问答-------------------- --------------------编程问答-------------------- 如果你想要我可以提供组件的方式给你,是很成熟的代码,在我的很多系统中都用到 --------------------编程问答-------------------- 行,十分感谢。
我的邮箱是cuihanfeng123@163.com,万分感谢...... --------------------编程问答-------------------- 我很想要,分数可以加。我的邮箱是cuihanfeng123@163.com,拜托了,高手! --------------------编程问答-------------------- 我很想要,分数可以加。我的邮箱是fangyufeng@163.com,拜托了,高手! --------------------编程问答-------------------- 好像可以用WCF来实现! --------------------编程问答--------------------

Imports System.Text.RegularExpressions


Imports System.Xml
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Diagnostics

Public Class frmServer
    Private Delegate Sub TxtDisplayInfoDelegate(ByVal Text As String)
    Dim cliSocket As Socket
    Dim ReceiveIP As String
    Dim ReceiveWord As String
    Dim ReceiveName As String
    Dim ReceiveTime As String
    Dim SelectIP As String
    Dim SelectName As String
    Dim IsEnterSendData As Boolean = False
    Dim ServerIP As String
    Dim StopThread As Boolean = False

    Public Class StateObject
        ' Client  socket.
        Public workSocket As Socket = Nothing
        ' Size of receive buffer.
        Public Const BufferSize As Integer = 4096
        ' Receive buffer.
        Public buffer(BufferSize) As Byte
        ' Received data string.
        Public sb As New StringBuilder

    End Class 'StateObject

    '服务端的Socket
    Dim listener As Socket
    '与客户端会话的Socket
    Dim mySocket As Socket
    '服务端的运行状态
    Dim IsRun As Boolean = False
    '监听接收数据线程
    Dim myThread As Thread
    Public allDone As New ManualResetEvent(False)

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'XMLServer()
        Start()
        btnSend.Enabled = False
        XMLShow()
        TextBox1.SelectionColor = Color.Blue
        Label2.Text = Dns.GetHostEntry(Dns.GetHostName).AddressList().GetValue(0).ToString
    End Sub

    Private Sub XMLShow()
        ListBox2.Items.Clear()
        Dim xmlDoc As New XmlDataDocument
        xmlDoc.Load(Application.StartupPath & "\UserDef.xml")
        Dim xn As XmlNode = xmlDoc.SelectSingleNode("collect")
        Dim xnl As XmlNodeList = xn.ChildNodes
        Dim xnf As XmlNode
        For Each xnf In xnl
            Dim xe As XmlElement = CType(xnf, XmlElement)
            If xe.GetAttribute("IP") <> "" Then
                ListBox2.Items.Add(xe.InnerText) '& vbCrLf  '显示属性值   
            End If
        Next xnf
    End Sub
    Private Sub XMLServer()
        Dim xmlDoc As New XmlDataDocument
        xmlDoc.Load(Application.StartupPath & "\UserDef.xml")
        Dim xn As XmlNode = xmlDoc.SelectSingleNode("collect")
        Dim xnl As XmlNodeList = xn.ChildNodes
        Dim xnf As XmlNode
        For Each xnf In xnl
            Dim xe As XmlElement = CType(xnf, XmlElement)
            If xe.GetAttribute("IP") <> "" Then
                ServerIP = xe.InnerText '& vbCrLf  '显示属性值   
                Debug.Print(ServerIP)
            End If
        Next xnf
    End Sub

    Private Sub Start()
        myThread = New Thread(AddressOf Listen)
        myThread.Start()
    End Sub
    Public Sub Listen()
        Try
            Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName)
            Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
            Dim localEndPoint As New IPEndPoint(ipAddress, 11000)

            '初始化socket
            listener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            '绑定端口
            listener.Bind(localEndPoint)
            '开始监听
            listener.Listen(10)

            BeginInvoke(New EventHandler(AddressOf AddInfo), "本地服务端已启动,正在等待连接......")
            StartListen()
        Catch ex As Exception
            MsgBox("错误" + ex.ToString, MsgBoxStyle.Information, "Listen")
        End Try
    End Sub
    Public Sub StartListen()

        Dim bytes() As Byte = New [Byte](1024) {}
        Dim data As String = String.Empty
        Try

            While True
                If StopThread = False Then
                    allDone.Reset()
                    listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
                    IsRun = True
                    allDone.WaitOne()
                Else
                    Exit Sub
                End If
            End While

        Catch ex As Exception
            MsgBox("错误" + ex.ToString, MsgBoxStyle.Information, "StartListen")
        End Try
    End Sub
--------------------编程问答--------------------

 Public Sub AcceptCallback(ByVal ar As IAsyncResult)
        ' Get the socket that handles the client request.
        Dim listener As Socket = CType(ar.AsyncState, Socket)
        ' End the operation.
        Dim handler As Socket = listener.EndAccept(ar)

        ' Create the state object for the async receive.
        Dim state As New StateObject
        state.workSocket = handler
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Debug.Print("AcceptCallback")
    End Sub
    Public Sub ReadCallback(ByVal ar As IAsyncResult)
        Dim content As String = String.Empty

        ' Retrieve the state object and the handler socket
        ' from the asynchronous state object.
        Dim state As StateObject = CType(ar.AsyncState, StateObject)
        Dim handler As Socket = state.workSocket

        ' Read data from the client socket. 
        Dim bytesRead As Integer = handler.EndReceive(ar)

        If bytesRead > 0 Then
            ' There  might be more data, so store the data received so far.
            state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead))

            ' Check for end-of-file tag. If it is not there, read 
            ' more data.
            content = state.sb.ToString()
            If content.IndexOf("<EOF>") > -1 Then
                ' All the data has been read from the 
                ' client. Display it on the console.
                Dim tokens() As String
                tokens = content.Trim.Split("|")
                ReceiveIP = tokens(0)
                ReceiveWord = tokens(1)
                ReceiveTime = tokens(2)
                Debug.Print(content)
                Dim del As New TxtDisplayInfoDelegate(AddressOf DisplayStatus)
                'Me.Invoke(del, "Read {0} bytes from socket. " + vbLf + " Data : {1}" & content.Length & content.ToString)
                Me.Invoke(del, content.ToString)
            Else
                ' Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
            End If
        End If

        handler.Shutdown(SocketShutdown.Both)
        handler.Close()
        ' Signal the main thread to continue.

        allDone.Set()

        Debug.Print("ReadCallback")
    End Sub 'ReadCallback
    Private Function GetReceiveName() As String
        Dim xmlDoc As New XmlDataDocument
        xmlDoc.Load(Application.StartupPath & "\UserDef.xml")
        Dim xnl As XmlNodeList = xmlDoc.SelectSingleNode("collect").ChildNodes
        Dim xn As XmlNode
        For Each xn In xnl
            Dim xe As XmlElement = CType(xn, XmlElement)
            If xe.GetAttribute("IP") = ReceiveIP Then
                GetReceiveName = xe.InnerText
                Exit Function
            End If
        Next xn
        GetReceiveName = ReceiveIP
    End Function
    Private Sub DisplayStatus(ByVal Text As String)
        'Me.ListBox1.Items.Add(SelectName & " 说: " & ReceiveWord)
        If IsEnterSendData = True Then
            Me.RichTextBox1.Text = Trim(Me.RichTextBox1.Text) & GetReceiveName() & "说:     " & ReceiveTime & vbCrLf & "     " & Trim(ReceiveWord)
        Else
            Me.RichTextBox1.Text = Trim(Me.RichTextBox1.Text) & GetReceiveName() & "说:     " & ReceiveTime & vbCrLf & "     " & Trim(ReceiveWord) & vbCrLf
        End If
        RichTextBox1.SelectionStart = RichTextBox1.TextLength
        RichTextBox1.Focus()
        PlaySound()
        TextBox1.Focus()

        'ListBox1.SelectedIndex = ListBox1.Items.Count - 1
    End Sub

    '发送信息
    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

        IsEnterSendData = False
        SendDataToServer()
    End Sub

    Private Sub SendDataToServer()
        If SelectIP = "" Then
            MsgBox("提示:没有选择发送对象!", MsgBoxStyle.Information, "MyQQ")
            Exit Sub
        End If
        Dim remoteEP As New IPEndPoint(Net.IPAddress.Parse("10.178.149.106"), 11000)
        cliSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Try
            cliSocket.Connect(remoteEP)
            'ListBox1.Items.Add("连接服务端成功!")

            Dim msg As Byte() = Encoding.UTF8.GetBytes("|" & SelectIP & "|" & Trim(TextBox1.Text) & "|" & Now() & "|" & "<EOF>")
            Dim bytesSent As Integer = cliSocket.Send(msg)
            If IsEnterSendData = True Then
                Me.RichTextBox1.Text = Me.RichTextBox1.Text & "本地消息:      " & Now() & vbCrLf & "     " & Trim(TextBox1.Text)
            Else
                Me.RichTextBox1.SelectionColor = Color.Blue

                Me.RichTextBox1.Text = Trim(Me.RichTextBox1.Text) & "本地消息:      " & vbCrLf & "     " & Trim(TextBox1.Text) & Chr(13) + Chr(0)
            End If
            RichTextBox1.SelectionStart = RichTextBox1.TextLength
            RichTextBox1.Focus()
            TextBox1.Focus()
            'ListBox1.Items.Add("本地信息: " + TextBox1.Text)
            'ListBox1.SelectedIndex = ListBox1.Items.Count - 1
            TextBox1.Text = ""
            'ListBox1.Items.Add(CStr(ListBox1.Items.Count + 1))
            cliSocket.Shutdown(Net.Sockets.SocketShutdown.Both)
            '禁用某 Socket 上的发送和接收
            cliSocket.Close()
            '关闭socket

        Catch ex As Exception
            MsgBox("无法连接到远程服务器由于目标机器积极拒绝,无法连接", MsgBoxStyle.Critical, "AGVExtend")
        End Try
    End Sub

    '非UI线程调用窗体控件,保证线程安全。与聊天实现无关。
    Sub AddInfo(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'ListBox1.Items.Add("信息: " + sender.ToString)
        Me.RichTextBox1.Text = Me.RichTextBox1.Text & "信息: " + sender.ToString & vbCrLf
    End Sub

    '关闭窗口时发关退出信息并清理资源
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            StopThread = True
            allDone.Set()
            myThread.Abort()
        Catch ex As Exception
            MsgBox("错误", MsgBoxStyle.Information, "Form1_FormClosing")
        End Try

    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If e.KeyChar = Chr(13) Then
            IsEnterSendData = True
            SendDataToServer()
        End If
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        If TextBox1.Text = "" Then
            btnSend.Enabled = False
        Else
            btnSend.Enabled = True
        End If
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Form2.ShowDialog()
        Me.XMLShow()
    End Sub


    Private Sub ListBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox2.SelectedIndexChanged
        If ListBox2.SelectedItems.Count = 0 Then Exit Sub
        Dim xmlDoc As New XmlDataDocument
        xmlDoc.Load(Application.StartupPath & "\UserDef.xml")
        Dim xnl As XmlNodeList = xmlDoc.SelectSingleNode("collect").ChildNodes
        Dim xn As XmlNode
        For Each xn In xnl
            Dim xe As XmlElement = CType(xn, XmlElement)
            If xe.InnerText = ListBox2.SelectedItems(0) Then
                SelectName = xe.InnerText
                SelectIP = xe.GetAttribute("IP")
                Debug.Print(SelectName)
                Debug.Print(SelectIP)
            End If
        Next xn

        Me.Text = "你正在与" & SelectName & " 通讯"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub

    Private Sub 关于ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 关于ToolStripMenuItem.Click
        AboutBox1.ShowDialog()
    End Sub

    Private Sub PlaySound()
        Try
            Dim myplayer As New System.Media.SoundPlayer()
            Dim myfilename As String = Application.StartupPath + "\Sound\msg.wav"
            myplayer.SoundLocation = myfilename
            myplayer.LoadAsync()
            myplayer.Play()
        Catch ex As Exception
            Err.Clear()
        End Try
    End Sub
End Class
--------------------编程问答--------------------
引用 楼主 cuihanfeng 的回复:
这是服务器端代码,怎么修改成多客户端的服务器端代码,万分感谢!
直接说你调试出这段代码有什么问题吧!
--------------------编程问答-------------------- 線程吧!
补充:.NET技术 ,  VB.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,