VB.NET: System.ArgumentOutOfRangeException - vb.net

Im attempting to make a multi-threaded socket program that communicates via TCP. I have followed this tutorial but get the following error.
P.S Im new at network programming
Here is the Stack Trace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at Multi_TCP_Server.Module1.handleClinet.doChat() in \Multi-TCP_Server\Module1.vb:line 57
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Here is Server code: (Multi-TCP_Server.vb)
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim LocalAddr As IPAddress = IPAddress.Parse("192.168.1.10")
Dim serverSocket As New TcpListener(LocalAddr, 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 handleClinet
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 handleClinet
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
End Module
And Here is the Client Code: (Multi-TCP_Client.vb)
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim serverStream As NetworkStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("Message from Client")
serverStream.Write(outStream, 32, outStream.Length)
'serverStream.Flush()
Dim inStream(10024) As Byte
buffSize = inStream.Length
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)
msg("Data from Server : " + returndata)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
msg("Client Started")
Try
clientSocket.Connect("192.168.1.10", 8888)
ConnectionStatusLbl.Text = "Server Connected..."
Catch ex As Exception
ConnectionStatusLbl.Text = "Unable to connect."
End Try
End Sub
Sub msg(ByVal mesg As String)
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg
End Sub
End Class
All help and ideas are appreciated.
Thanks :)
EDIT: Here is the Stack Trace from Multi-TCP_Client.vb

Related

VB.NET TCP Server/Client - Get IP of connected client

I'm trying to get the IP address of the connected client but I don't know what I doing wrong. Where I can find it? I think near Sub AcceptClient. I was trying to convert cClient to string, but it always results to True or False. I'm trying to get the argument ar from cClient, which gives me an empty result.
Client.Client.RemoteEndPoint doesn't work or I can't use it correctly.
Form1.vb from Server project
Imports System.IO, System.Net, System.Net.Sockets
Public Class Form1
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ClientList As New List(Of ChatClient)
Dim sReader As StreamReader
Dim cClient As ChatClient
Sub xLoad() Handles Me.Load
Listener = New TcpListener(IPAddress.Any, 3818)
Timer1.Start()
Listener.Start()
xUpdate("Server Started", False)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''Set view property
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
'Add column header
ListView1.Columns.Add("Adres IP", 120)
ListView1.Columns.Add("Nazwa użytkownika", 120)
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
cClient = New ChatClient(Listener.EndAcceptTcpClient(ar))
AddHandler(cClient.MessageRecieved), AddressOf MessageRecieved
AddHandler(cClient.ClientExited), AddressOf ClientExited
ClientList.Add(cClient)
xUpdate("New Client Joined", True)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub MessageRecieved(ByVal Str As String)
xUpdate(Str, True)
End Sub
Sub ClientExited(ByVal Client As ChatClient)
ClientList.Remove(Client)
xUpdate("Client Exited", True)
End Sub
Delegate Sub _xUpdate(ByVal Str As String, ByVal Relay As Boolean)
Sub xUpdate(ByVal Str As String, ByVal Relay As Boolean)
On Error Resume Next
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), Str, Relay)
Else
Dim nStart As Integer
Dim nLast As Integer
If Str.Contains("</>") Then
nStart = InStr(Str, "</></>") + 7
nLast = InStr(Str, "<\><\>")
Str = Mid(Str, nStart, nLast - nStart)
'dzielenie strina po odpowiednim syymbolu na przed i po symbolu :D
Dim mystr As String = Str
Dim cut_at As String = ","
Dim x As Integer = InStr(mystr, cut_at)
Dim string_before As String = mystr.Substring(0, x - 1)
Dim string_after As String = mystr.Substring(x + cut_at.Length - 1)
Dim otherItems As String() = {string_after}
ListView1.Items.Add(string_before).SubItems.AddRange(otherItems) 'use SubItems
ElseIf Str.Contains("<A>") Then
nStart = InStr(Str, "<A>") + 4
nLast = InStr(Str, "<B>")
Str = Mid(Str, nStart, nLast - nStart)
ListBox2.Items.Add(Str & vbNewLine)
Else
TextBox1.AppendText(Str & vbNewLine)
If Relay Then Send(Str & vbNewLine)
End If
End If
End Sub
Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
xUpdate("Server Says: " & TextBox2.Text, True)
TextBox2.Clear()
End If
End Sub
Sub Send(ByVal Str As String)
For i As Integer = 0 To ClientList.Count - 1
Try
ClientList(i).Send(Str)
Catch
ClientList.RemoveAt(i)
End Try
Next
End Sub
End Class
ChatClient.vb from Server project
Imports System.Net.Sockets, System.IO
Public Class ChatClient
Public Event MessageRecieved(ByVal Str As String)
Public Event ClientExited(ByVal Client As ChatClient)
Private sWriter As StreamWriter
Public Client As TcpClient
Sub New(ByVal xclient As TcpClient)
Client = xclient
client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
End Sub
Private Sub Read()
Try
Dim sr As New StreamReader(Client.GetStream)
Dim msg As String = sr.ReadLine()
RaiseEvent MessageRecieved(msg)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf Read), Nothing)
Catch
RaiseEvent ClientExited(Me)
End Try
End Sub
Public Sub Send(ByVal Message As String)
sWriter = New StreamWriter(Client.GetStream)
sWriter.WriteLine(Message)
sWriter.Flush()
End Sub
End Class
You can get the IP address from the underlying socket by converting the Socket.RemoteEndPoint property into an IPEndPoint:
Dim Address As IPAddress = CType(cClient.Client.Client.RemoteEndPoint, IPEndPoint).Address
MessageBox.Show(Address.ToString()) 'Example.

An empty file after sending file to tcp server

I try to sort out this code i have manage do make it works but then wen i try to send the file from the client to the server then the file its come empty and with no extension.
well i have try some examples from internet but i can not get it work correctly
this is my code
Imports System.Threading
Imports System.Net.Sockets
Imports System.IO
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Visible = False
RECIBE()
End Sub
Public Sub RECIBE()
Dim CLIENTE As TcpClient
Dim TAMAÑOBUFFER As Integer = 1024
Dim ARCHIVORECIBIDO As Byte() = New Byte(TAMAÑOBUFFER - 1) {}
Dim BYTESRECIBIDOS As Integer
Dim FIN As Integer = 0
Dim SERVIDOR As New TcpListener(IPAddress.Any, 8080)
SERVIDOR.Start()
While FIN = 0
Dim NS As NetworkStream = Nothing
Try
Dim ACEPTA As String = "ACEPTA EL FICHERO ENTRANTE"
Dim TITULO As String = "FICHERO ENTRANTE"
Dim BOTONES As MessageBoxButtons = MessageBoxButtons.YesNo
Dim RESULTADO As DialogResult
If SERVIDOR.Pending Then
CLIENTE = SERVIDOR.AcceptTcpClient
NS = CLIENTE.GetStream
RESULTADO = MessageBox.Show(ACEPTA, TITULO, BOTONES)
If RESULTADO = Windows.Forms.DialogResult.Yes Then
Dim FICHERORECIBIDO As String = Nothing
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
FICHERORECIBIDO = SaveFileDialog1.FileName
Label1.Text = FICHERORECIBIDO
End If
If FICHERORECIBIDO <> String.Empty Then
Dim TOTALBYTESRECIBIDOS As Integer = 0
Dim FS As New FileStream(FICHERORECIBIDO, FileMode.OpenOrCreate, FileAccess.Write)
While (AYUDAENLINEA(BYTESRECIBIDOS, NS.Read(ARCHIVORECIBIDO, 0, ARCHIVORECIBIDO.Length))) > 0
FS.Write(ARCHIVORECIBIDO, 0, BYTESRECIBIDOS)
TOTALBYTESRECIBIDOS = TOTALBYTESRECIBIDOS + BYTESRECIBIDOS
End While
FS.Close()
End If
NS.Close()
CLIENTE.Close()
'SERVIDOR.Stop()
MsgBox("DESCARGA FINALIZADA")
FIN = 1
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End While
SERVIDOR.Stop()
Button1.Visible = True
End Sub
Private Shared Function AYUDAENLINEA(Of T)(ByRef OBJETIVO As T, VALOR As T)
OBJETIVO = VALOR
Return VALOR
End Function
End Class
client side sender
This is my code
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim TAMAÑOBUFFER As Integer = 1024
Try
Dim CLIENTE As New TcpClient(TextBox2.Text, TextBox3.Text)
Dim NS As NetworkStream = CLIENTE.GetStream
Dim FS As New FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read)
Dim PAQUETES As Integer = CInt(Math.Ceiling(CDbl(FS.Length) / CDbl(TAMAÑOBUFFER)))
Dim LONGITUDTOTAL As Integer = CInt(FS.Length)
Dim LONGITUDPAQUETEACTUAL As Integer = 0
Dim CONTADOR As Integer = 0
For I As Integer = 0 To PAQUETES - 1
If LONGITUDTOTAL > TAMAÑOBUFFER Then
LONGITUDPAQUETEACTUAL = TAMAÑOBUFFER
LONGITUDTOTAL = LONGITUDTOTAL - LONGITUDPAQUETEACTUAL
Else
LONGITUDPAQUETEACTUAL = LONGITUDTOTAL
End If
Dim ENVIARBUFFER As Byte() = New Byte(LONGITUDPAQUETEACTUAL - 1) {}
FS.Read(ENVIARBUFFER, 0, LONGITUDPAQUETEACTUAL)
NS.Write(ENVIARBUFFER, 0, CInt(ENVIARBUFFER.Length))
Next
FS.Close()
NS.Close()
CLIENTE.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

Client to client direct chat through server vb.net

Using socket programming, I'm developing a chatting application using vb.net. I have manage to established group chat using a server and multi-client. Now i want to establish a client to client direct chat through server and want to list down all connected clients. If anyone can guide me would be very helpful.
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim clientsList As New Hashtable
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
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("$"))
clientsList(dataFromClient) = clientSocket
broadcast(dataFromClient + " Joined ", dataFromClient, False)
msg(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
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
Private Sub broadcast(ByVal msg As String, _
ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = _
broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
'Dim infiniteCounter As Integer
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)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
End Class
End Module

Pass data/parameter to socket thread using VB Net

am running two TCP servers(one in 50010 and other in 10250) in my code both in separate thread
Private Sub frmMainScreen_Load(ByVal eventSender As Object, ByVal eventArgs As EventArgs) Handles MyBase.Load
Dim Local_PortNum As String = Read_GlobalINI_File("TCP-IP CONFIGURATION", "LOCAL_PORT", "TCPIP_Config")
Read_FileLocation()
Dim s As New ClsAutomation_TcpClient
Dim t As New ClsAutomation_TcpClient
trd = New Thread(Sub() s.Main()) ' listens 55000 port
trd1 = New Thread(Sub() t.Main())' listens 10250 port
trd.IsBackground = True
trd.Start()
trd1.IsBackground = True
trd1.Start()
End Sub
here is my tcpserver class
Public Class ClsAutomation_TcpClient
Dim clientsList As New Hashtable
Public WithEvents status_bar1 As System.Windows.Forms.Label
Sub Main()
Dim serverSocket As New TcpListener(IPAddress.Any, 10250)
Dim clientSocket As TcpClient
Dim counter As Integer
Dim clientIPAddress As String
serverSocket.Start()
MsgBox("Chat Server Started ....")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
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("$"))
Dim ipend As Net.IPEndPoint = clientSocket.Client.RemoteEndPoint
clientIPAddress = ipend.Address.ToString()
clientsList(clientIPAddress) = clientSocket
broadcast(clientIPAddress + " Joined ", dataFromClient, False)
' MsgBox(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
End While
clientSocket.Close()
serverSocket.Stop()
MsgBox("exit")
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
MsgBox(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
End Class
Public Class handleClinet
Public WithEvents status_bar1 As System.Windows.Forms.Label
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub broadcast(ByVal msg As String, ByVal uName As String, ByVal flag As Boolean)
'Dim Item As DictionaryEntry
'For Each Item In clientsList
Dim broadcastSocket As TcpClient
'broadcastSocket = CType(Item.Value, TcpClient)
broadcastSocket = Me.clientSocket
Dim broadcastStream As NetworkStream = broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
'Next
End Sub
Private Sub doChat()
'Dim infiniteCounter As Integer
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("$"))
'MsgBox("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
End Class
Here what i need to do is send data from a btn_click to the (trd) 55000 instance thread...
how would i do it
Your question is quite broad but in simple terms:
You need to create a NetworkStream object.
Assign this using the TcpClient.GetStream method and then call NetworkStream.Write
Something like this (untested) code:
Dim stream as NetworkStream
stream = clientSocket.GetStream
Dim buffer() as byte = System.Text.Encoding.ASCII.GetBytes("hello")
If stream.CanWrite Then stream.Write(buffer, 0, buffer.Length)

vb.net multi thread chat client and server

i have created a chat server for chatting. there i connect the client pc's that will allow to chat them. In my case, server allow me to connect with that, but i can't able to chat with others make use of my application. Please see my code and correct it. here is my code.
Client side code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Dim readData As String
Dim infiniteCounter As Integer
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox2.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
End Sub
Private Sub msg()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf msg))
Else
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + readData
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
readData = "Conected to Chat Server ..."
msg()
clientSocket.Connect("192.168.1.215", 8888)
'Label1.Text = "Client Socket Program - Server Connected ..."
serverStream = clientSocket.GetStream()
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox3.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf getMessage)
ctThread.Start()
End Sub
Private Sub getMessage()
For infiniteCounter = 1 To 2
infiniteCounter = 1
serverStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim inStream(10024) As Byte
buffSize = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
readData = "" + returndata
msg()
Next
End Sub
End Class
server side Code:
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim clientsList As New Hashtable
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim infiniteCounter As Integer
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
infiniteCounter = 0
For infiniteCounter = 1 To 2
infiniteCounter = 1
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
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("$"))
clientsList(dataFromClient) = clientSocket
broadcast(dataFromClient + " Joined ", dataFromClient, False)
msg(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
Next
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, _
ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = _
broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
Dim infiniteCounter As Integer
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
For infiniteCounter = 1 To 2
infiniteCounter = 1
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)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
End Sub
End Class
End Module
One, you need to specify your PUBLIC IP address, second, you need to open port 8888 on your router.
Change: clientSocket.Connect("192.168.1.215", 8888) to:
clientSocket.Connect("", 8888)
And make sure to forward port 8888 to your internal LAN IP: 192.168.1.215
Also this is entirely unsecure, I would encrypt and decrypt the strings using triple DES. A little bit of security but at least its security.
Learn a bit about networking bud.