Visual Basic Development Bookmark and Share   
 Home > Visual Basic Language > help on a console based socket app
 

help on a console based socket app

i have made a console based socket program in vb.net, all it does2 things: 1-server shows a msgbox when the command msg is sent from the client
2- the server opens the cd try when the command open is sent form the client

so my question is : when i run it , i type the command open and works just fine , the cd tray opens , but if i type open again or msg it simply wont do anything(this also applies for the command msg, if type it a msg is shown, but if i type it agine or open , it wont respond. so its like one command per session.

i tried to put the code in a while loop , but didnt work(am not sure if i did it the right way)

so plz help

here is the code for the server:


Imports System.IO
Imports System.Net.Sockets


Module Module1

Private setTrayStatus As Long

Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" _
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer




Sub Main()
Console.WriteLine("")
Dim clientListener As New TcpListener(8585)


clientListener.Start()


Console.WriteLine("")
Dim mySocket As Socket = clientListener.AcceptSocket()


Console.WriteLine("")


Dim recieveBuff(10) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))

If str = "open" Then
setTrayStatus = mciSendString("Set CDAudio Door Open", Nothing, 0, 0)
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
ElseIf str = "close" Then
setTrayStatus = mciSendString("Set CDAudio Door Closed", Nothing, 0, 0)
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
ElseIf str = "msg" Then
MsgBox("hello", MsgBoxStyle.OkCancel, "msg form client")
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
End If
End Sub
End Module



and the code for the client :



Imports System.IO
Imports System.Net.Sockets


Module Module1


Sub Main()


Try
Console.WriteLine("Connecting to 8585 Local Host")
Dim serverListener As New TcpClient("localhost", 8585)
Dim readStream As Stream = serverListener.GetStream

Console.WriteLine("Input Lines:")
Dim str As String = Console.ReadLine()


While True
Dim sendBuff As Byte() = System.Text.Encoding.ASCII.GetBytes(str)


readStream.Write(sendBuff, 0, sendBuff.Length)


If str.StartsWith(".") Then
GoTo Done
End If


str = Console.ReadLine()
End While


Done: Console.WriteLine("Done")


Catch exp As Exception


Console.WriteLine("Exception: " + exp.ToString())


End Try


End Sub


End Module


thanks in advance

xjpx  Monday, August 03, 2009 11:08 AM
This is a very quick and dirty example. It would be much better off written using async methods, but anyway....

Server:
Option Explicit On
Option Strict On

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



Module MainModule

    Private Declare Auto Function mciSendString Lib "winmm.dll" Alias "mciSendString" _
     (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
      ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer

    'Private _exit As Boolean

    Sub Main()
        Console.Clear()

        Console.WriteLine("Starting Server...")
        Dim t As New Thread(AddressOf RunServer)
        Dim server As New TcpListener(IPAddress.Loopback, 8585)
        t.Start(server)
        Console.ReadLine()

        server.Stop()
        '_exit = True
        t.Join(10000)
        Console.WriteLine("Bye")
    End Sub

    Sub RunServer(ByVal param As Object)
        Dim server As TcpListener = TryCast(param, TcpListener)
        server.Start()

        While True
            Try
                Dim client As TcpClient = server.AcceptTcpClient()
                Using reader As New StreamReader(client.GetStream())
                    Dim command = reader.ReadLine().ToLower()

                    Select Case command
                        Case "open"
                            mciSendString("Set CDAudio Door Open", Nothing, 0, 0)
                        Case "close"
                            mciSendString("Set CDAudio Door Closed", Nothing, 0, 0)
                        Case "msg"
                            Console.WriteLine("msg from client")
                        Case Else
                            Console.WriteLine("bogus input")
                    End Select

                End Using
            Catch
                Exit While
            End Try
        End While
    End Sub

End Module

Client:
Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Module Module1

    Sub Main()
        Dim command As String
        Do
            Console.Clear()
            Console.Write("Enter a command: ")
            command = Console.ReadLine()
            If command.Length > 0 Then
                SendCommand(command)
            End If
        Loop Until String.IsNullOrEmpty(command)
    End Sub

    Sub SendCommand(ByVal command As String)
        Using client As New TcpClient()
            client.Connect(IPAddress.Loopback, 8585)
            Using writter As New StreamWriter(client.GetStream())
                writter.WriteLine(command)
            End Using
        End Using
    End Sub
End Module

HTH
Tom Shelton
  • Marked As Answer byxjpx Wednesday, August 05, 2009 9:55 AM
  • Proposed As Answer bynillebo Tuesday, August 04, 2009 8:43 PM
  •  
Tom Shelton  Monday, August 03, 2009 6:16 PM
This is a very quick and dirty example. It would be much better off written using async methods, but anyway....

Server:
Option Explicit On
Option Strict On

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



Module MainModule

    Private Declare Auto Function mciSendString Lib "winmm.dll" Alias "mciSendString" _
     (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
      ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer

    'Private _exit As Boolean

    Sub Main()
        Console.Clear()

        Console.WriteLine("Starting Server...")
        Dim t As New Thread(AddressOf RunServer)
        Dim server As New TcpListener(IPAddress.Loopback, 8585)
        t.Start(server)
        Console.ReadLine()

        server.Stop()
        '_exit = True
        t.Join(10000)
        Console.WriteLine("Bye")
    End Sub

    Sub RunServer(ByVal param As Object)
        Dim server As TcpListener = TryCast(param, TcpListener)
        server.Start()

        While True
            Try
                Dim client As TcpClient = server.AcceptTcpClient()
                Using reader As New StreamReader(client.GetStream())
                    Dim command = reader.ReadLine().ToLower()

                    Select Case command
                        Case "open"
                            mciSendString("Set CDAudio Door Open", Nothing, 0, 0)
                        Case "close"
                            mciSendString("Set CDAudio Door Closed", Nothing, 0, 0)
                        Case "msg"
                            Console.WriteLine("msg from client")
                        Case Else
                            Console.WriteLine("bogus input")
                    End Select

                End Using
            Catch
                Exit While
            End Try
        End While
    End Sub

End Module

Client:
Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Module Module1

    Sub Main()
        Dim command As String
        Do
            Console.Clear()
            Console.Write("Enter a command: ")
            command = Console.ReadLine()
            If command.Length > 0 Then
                SendCommand(command)
            End If
        Loop Until String.IsNullOrEmpty(command)
    End Sub

    Sub SendCommand(ByVal command As String)
        Using client As New TcpClient()
            client.Connect(IPAddress.Loopback, 8585)
            Using writter As New StreamWriter(client.GetStream())
                writter.WriteLine(command)
            End Using
        End Using
    End Sub
End Module

HTH
Tom Shelton
  • Marked As Answer byxjpx Wednesday, August 05, 2009 9:55 AM
  • Proposed As Answer bynillebo Tuesday, August 04, 2009 8:43 PM
  •  
Tom Shelton  Monday, August 03, 2009 6:16 PM
thanks ,

really helped
xjpx  Tuesday, August 04, 2009 10:37 AM

You can use google to search for other answers

Custom Search

More Threads

• A small Educational Program to show us a technique for one Button Invoking/Triggering another Button! Finished by John Oliver! Works!
• How can I let a user select the location of a database?
• Interfacing VB app with C++ plugin
• Setting Folder Attribute to Compressed
• Rich Text Box Append Text with color
• Adding Buttons to TabPages at runtime
• Connecting to SQL server within a program.
• Packets Get&Read/Send
• Bug in Constant Folding?
• Change background color of certain lines in richtextbox