|
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Diagnostics
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_Startup(ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) _
Handles Me.Startup
Dim server As TcpListener = Nothing
Try
' 50000 番ポート使用
Dim port As Int32 = 50000
' ローカル
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
server = New TcpListener(localAddr, port)
' サーバー開始
server.Start()
' 読み込みバッファ
Dim bytes(1024) As Byte
' コマンドワーク
Dim data As String = Nothing
Console.WriteLine("Waiting ... ")
' 待機( 接続されると次の行へ )
Dim client As TcpClient = server.AcceptTcpClient()
' 受信したので処理開始
Console.WriteLine("Connected")
data = ""
' 受信用ストリーム
Dim stream As NetworkStream = client.GetStream()
Dim i As Integer
Dim cd As Integer = 0
' ストリームからデータを取得( 初回 )
i = stream.Read(bytes, 0, bytes.Length)
Do While i <> 0
cd = 0
For idx As Integer = 0 To i - 1
If bytes(idx) = &HD Then
cd += 1
End If
If cd = 0 Then
data += _
Encoding.ASCII.GetString(bytes, idx, 1)
End If
If bytes(idx) = &HA And cd = 1 Then
' 改行区切りでコマンドを取得
Console.WriteLine("Received: {0}", data)
If data = "quit" Then
Exit Do
Else
Dim delimStr As String = "|"
Dim delimiter As Char() = delimStr.ToCharArray()
' 配列定義
Dim split As String() = Nothing
' トークン分割
split = data.Split(delimiter)
Try
If split.Length = 1 Then
Process.Start(data)
Else
Process.Start(split(0), split(1))
End If
Catch ex As System.ComponentModel.Win32Exception
Dim errmsg As Byte() = _
Encoding.ASCII.GetBytes("ERROR" _
+ ControlChars.CrLf)
stream.Write(errmsg, 0, errmsg.Length)
cd = 0
data = ""
Exit For
End Try
End If
cd = 0
data = ""
' OK を返す
Dim msg As Byte() = _
Encoding.ASCII.GetBytes("OK" + ControlChars.CrLf)
stream.Write(msg, 0, msg.Length)
End If
Next
' ストリームからデータを取得
i = stream.Read(bytes, 0, bytes.Length)
Loop
' 処理終了で接続解除してサービス終了
client.Close()
Catch ex As SocketException
Console.WriteLine("SocketException: {0}", ex)
Finally
server.Stop()
End Try
e.Cancel = True
End Sub
End Class
End Namespace
| |