473,804 Members | 3,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Please help, Sockets / Threading

Hello Everyone

I am making an instant messenger program. I have used the MSDN sockets example to get started with this. I have transfered the code that is found within this project into a class and can access it fine

The problem is, that the messenger sends a message to the server which relays the message to the correct user: great, but there is a thread running that is reading the incomming data and passes it to a process sub that checks to see what the server has sent

Now i am trying to get a new instance of a form to load up when a message is received but when it runs the form loads up but just lags and doesnt load properly, its like its trying to do the same thing over and over again

Its weird because data gets sent to the server - > server sends to the client - > client opens a new window ( this lags ), but there is only one lot of data and it just keeps lagging like it is doing it over and over and over. How can i get this to work

If you need some code examples, just get me on my msn which is ma**@xoolo.net ( THIS IS NOT MY EMAIL JUST MSN )

Thanks to anyone that can help.
Nov 20 '05 #1
10 1348
Matt wrote:
Hello Everyone,

I am making an instant messenger program. I have used the MSDN
sockets example to get started with this. I have transfered the code
that is found within this project into a class and can access it
fine.

The problem is, that the messenger sends a message to the server
which relays the message to the correct user: great, but there is a
thread running that is reading the incomming data and passes it to a
process sub that checks to see what the server has sent.

Now i am trying to get a new instance of a form to load up when a
message is received but when it runs the form loads up but just lags
and doesnt load properly, its like its trying to do the same thing
over and over again.


It sounds like you are trying to create the new form in the context of the
thread that handles the incoming data. This thread will typically block
until new data comes in, preventing your form, which is running in that
thread, from executing it's code.

What you want to do is create all your UI in the same threads. Create a
function that handles the 'create new form' bit. Create a delegate for this
function's signature, or have the signature match either the EventHandler or
MethodInvoker delegate, that's fastest. Now use the Invoke method on your
main form to run this function in your UI thread's context.

That should take care of it, unless I misunderstand your intentions.

--
Sven Groot
Nov 20 '05 #2
Hi Matt

I have also worked on similar project. I think you need to change your arch.... I will online tom... In my office msn is blocked. Tom... I will chat with you from my home. My MSN ID is sa************@ hotmail.com.

Sadha Sivam
Malleable Minds Software Pvt Ltd
Nov 20 '05 #3
Thats exactly what is happening Sven Groot, i am a new vb.net developer
what a change from vb6 hehe.

Anychance you could give me a quick example of what i have to do.

Here is where the code is happening:

THIS PART IS DONE ON THE FORM LOAD
----------------------------------------
Public Sub tryConnect()
Try
' The TcpClient is a subclass of Socket, providing higher
level
' functionality like streaming.
client = New TcpClient(strSe rver, PORT_NUM)

' Start an asynchronous read invoking DoRead to avoid
lagging the user
' interface.
client.GetStrea m.BeginRead(rea dBuffer, 0, READ_BUFFER_SIZ E,
AddressOf DoRead, Nothing)

Catch Ex As Exception
End
End Try
If strUsername > "" Then
'When the user first enters the program
'The connect command is sent to the server
SendData("CNT" & "|" & strUsername & "|" & strNickName)
End If
End Sub
-----------------------------------------
THIS PART IS NEXT
-----------------------------------------
Public Sub DoRead(ByVal ar As IAsyncResult)
Dim BytesRead As Integer
Dim strMessage As String

Try
' Finish asynchronous read into readBuffer and return number
of bytes read.
BytesRead = client.GetStrea m.EndRead(ar)
If BytesRead < 1 Then
' If no bytes were read server has close. Disable input
window.
Exit Sub
End If
' Convert the byte array the message was saved into, minus
two for the
'Chr(13) and Chr(10)
strMessage = Encoding.ASCII. GetString(readB uffer, 0,
BytesRead - 2)

-----------------------------------------
THIS PART OF THIS SUB IS WHERE IT CHECKS THE COMMANDS, PASSES TO ANOTHER
SUB
-----------------------------------------
ProcessCommands (strMessage)

' Start a new asynchronous read into readBuffer.
client.GetStrea m.BeginRead(rea dBuffer, 0, READ_BUFFER_SIZ E,
AddressOf DoRead, Nothing)
Catch e As Exception
MsgBox(e.Messag e)
End Try

End Sub
-----------------------------------------
THE FOLLOWING SUB PROCESSES THE COMMANDS
-----------------------------------------
Public Sub ProcessCommands (ByVal strMessage As String)
'TMSG|123456789 0|Matt|12345678 90|Message
Dim dataArray() As String
Dim lstR As ListViewItem
dataArray = Split(strMessag e, Chr(124))
Select Case dataArray(0)
Case "RNICK"
'lstR = lstContacts.Ite ms.Add(dataArra y(2))
'lstR.SubItems. Add(dataArray(1 ))
-----------------------------------------
THIS IS THE PROBLEM AREA, IDEALLY IT WOULD BE GOOD TO HAVE THIS WHOLE
SUB RUNNING OUT OF THE THREAD SO I CAN EXECUTE CODE HERE
-----------------------------------------
Case "TMSG"
'open message window
'display received message
'Open a new window, or open window with tabs
If F4 Is Nothing Then
F4 = New frmMessage
F4.Show()
End If
Case "ERROR"
MsgBox(dataArra y(1), MsgBoxStyle.Exc lamation, "An Error
Has Occured")
End Select
End Sub
-----------------------------------------

I would apprechiate any further help you can give me.

Kind Regards

Matt

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #4
ok
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #5
I aint done much with delegates but i know its something to do like:

Dim nForm As NewForm
-------------------------------------------
I dont really know where to put this or if im even doing it right, can
you help.
-------------------------------------------
nForm = New NewForm(Address Of createNewForm)
nForm.Invoke()
-------------------------------------------

Public Sub createNewForm()
If F4 Is Nothing Then
F4 = New frmMessage
F4.Show()
End If
End Sub

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #6
Matthew Lanham wrote:
Thats exactly what is happening Sven Groot, i am a new vb.net
developer what a change from vb6 hehe.
First of all, the class that holds the code you show below needs a reference
to the active instance of some other part of the UI. In VB6, this reference
will be globally available under the name of the form, in VB.NET it's not.
You need to explicitly put a variable in the class (or a global variable,
but if a member is possible use that, it's better from a design point of
view) with the ProcessCommands sub and set it to the instance of your main
form. Suppose we call that variable MainForm.

Now you create a function somewhere (most likely in the class with
ProcessMessage) that reads as follows:
Public Sub CreateNewForm()
If F4 Is Nothing Then
F4 = New frmMessage
F4.Show()
End If
End Sub

Because this sub has no parameters, you don't need to create your own
delegate type, it already matches the type of the MethodInvoker delegate.

Now in the ProcessMessage sub, where you'd normally execute the code from
above, you put:
MainForm.Invoke (New MethodInvoker(A ddressOf CreateNewForm))

This will cause the CreateNewForm method to run in the thread context of the
form MainForm points to, which is what you want.
THIS PART IS DONE ON THE FORM LOAD
----------------------------------------
Public Sub tryConnect()
Try
' The TcpClient is a subclass of Socket, providing higher
level
' functionality like streaming.
client = New TcpClient(strSe rver, PORT_NUM)

' Start an asynchronous read invoking DoRead to avoid
lagging the user
' interface.
client.GetStrea m.BeginRead(rea dBuffer, 0, READ_BUFFER_SIZ E,
AddressOf DoRead, Nothing)

Catch Ex As Exception
End
End Try
If strUsername > "" Then
'When the user first enters the program
'The connect command is sent to the server
SendData("CNT" & "|" & strUsername & "|" & strNickName)
End If
End Sub
-----------------------------------------
THIS PART IS NEXT
-----------------------------------------
Public Sub DoRead(ByVal ar As IAsyncResult)
Dim BytesRead As Integer
Dim strMessage As String

Try
' Finish asynchronous read into readBuffer and return
number of bytes read.
BytesRead = client.GetStrea m.EndRead(ar)
If BytesRead < 1 Then
' If no bytes were read server has close. Disable
input window.
Exit Sub
End If
' Convert the byte array the message was saved into, minus
two for the
'Chr(13) and Chr(10)
strMessage = Encoding.ASCII. GetString(readB uffer, 0,
BytesRead - 2)

-----------------------------------------
THIS PART OF THIS SUB IS WHERE IT CHECKS THE COMMANDS, PASSES TO
ANOTHER SUB
-----------------------------------------
ProcessCommands (strMessage)

' Start a new asynchronous read into readBuffer.
client.GetStrea m.BeginRead(rea dBuffer, 0, READ_BUFFER_SIZ E,
AddressOf DoRead, Nothing)
Catch e As Exception
MsgBox(e.Messag e)
End Try

End Sub
-----------------------------------------
THE FOLLOWING SUB PROCESSES THE COMMANDS
-----------------------------------------
Public Sub ProcessCommands (ByVal strMessage As String)
'TMSG|123456789 0|Matt|12345678 90|Message
Dim dataArray() As String
Dim lstR As ListViewItem
dataArray = Split(strMessag e, Chr(124))
Select Case dataArray(0)
Case "RNICK"
'lstR = lstContacts.Ite ms.Add(dataArra y(2))
'lstR.SubItems. Add(dataArray(1 ))
-----------------------------------------
THIS IS THE PROBLEM AREA, IDEALLY IT WOULD BE GOOD TO HAVE THIS WHOLE
SUB RUNNING OUT OF THE THREAD SO I CAN EXECUTE CODE HERE
-----------------------------------------
Case "TMSG"
'open message window
'display received message
'Open a new window, or open window with tabs
If F4 Is Nothing Then
F4 = New frmMessage
F4.Show()
End If
Case "ERROR"
MsgBox(dataArra y(1), MsgBoxStyle.Exc lamation, "An Error
Has Occured")
End Select
End Sub
-----------------------------------------


--
Sven Groot
Nov 20 '05 #7
Can you explain this part please, if you could edit the code i gave
showing me where to make the changes that would be brilliant.

I am trying to do this honestly.
------------------------------------------------------
First of all, the class that holds the code you show below needs a
reference to the active instance of some other part of the UI. In VB6,
this reference will be globally available under the name of the form, in
VB.NET it's not. You need to explicitly put a variable in the class (or
a global variable, but if a member is possible use that, it's better
from a design point of view) with the ProcessCommands sub and set it to
the instance of your main form. Suppose we call that variable MainForm.
------------------------------------------------------
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #8
Matthew Lanham wrote:
Can you explain this part please, if you could edit the code i gave
showing me where to make the changes that would be brilliant.

I am trying to do this honestly.
------------------------------------------------------
First of all, the class that holds the code you show below needs a
reference to the active instance of some other part of the UI. In VB6,
this reference will be globally available under the name of the form,
in VB.NET it's not. You need to explicitly put a variable in the
class (or a global variable, but if a member is possible use that,
it's better from a design point of view) with the ProcessCommands sub
and set it to the instance of your main form. Suppose we call that
variable MainForm.
------------------------------------------------------
Upon reading your code better, it would appear all these functions are
inside a single Form class. Am I right?

If so, you can pretty much ignore the paragraph above, and follow these
instructions. You say you want to run the entire ProcessCommands method in
another thread. That's certainly possible, but do note it will be slightly
slower than using a method that takes no parameters. Still, in your case
it's probably necessary to do it this way (or redesign a large part of your
code), because of some of the methods you call. You must keep in mind that
the System.Windows. Forms.Control class is not thread safe (all controls and
forms are children of this class). I quote the documentation:
"Note: There are four methods on a control that are safe to call from any
thread: Invoke, BeginInvoke, EndInvoke, and CreateGraphics. For all other
method calls, you should use one of the invoke methods to marshal the call
to the control's thread."

But back to the business at hand. You want to use Invoke to run
ProcessCommands in the UI thread, and since ProcessCommands has a non-empty
argument list you need a custom delegate type.

Add to the top of your form a declaration for this delegate type:
Private Delegate Sub ProcessCommands Delegate(ByVal strMessage As String)
-----------------------------------------
THIS PART IS NEXT
-----------------------------------------
Public Sub DoRead(ByVal ar As IAsyncResult)
Dim BytesRead As Integer
Dim strMessage As String

Try
' Finish asynchronous read into readBuffer and return
number of bytes read.
BytesRead = client.GetStrea m.EndRead(ar)
If BytesRead < 1 Then
' If no bytes were read server has close. Disable
input window.
Exit Sub
End If
' Convert the byte array the message was saved into, minus
two for the
'Chr(13) and Chr(10)
strMessage = Encoding.ASCII. GetString(readB uffer, 0,
BytesRead - 2)

-----------------------------------------
THIS PART OF THIS SUB IS WHERE IT CHECKS THE COMMANDS, PASSES TO
ANOTHER SUB
-----------------------------------------
ProcessCommands (strMessage)
Now, replace the call to ProcessCommands with the following:
Me.Invoke(New ProcessCommands Delegate(Addres sOf ProcessCommands ), _
New Object() {strMessage})

Now ProcessCommands gets run in the proper thread context.

' Start a new asynchronous read into readBuffer.
client.GetStrea m.BeginRead(rea dBuffer, 0, READ_BUFFER_SIZ E,
AddressOf DoRead, Nothing)
Catch e As Exception
MsgBox(e.Messag e)
Don't use MsgBox. It's the VB6 way. The .Net way is MessageBox.Show (). Also,
always(!) use the overloads that take an IWin32Window owner as their first
parameter. I've found it to be rather unreliable in picking the owner in
certain situations if you don't explicitly specify it, especially if you're
doing this in a different thread from the form that's supposed to be the
owner. Therefore, replace the call to MessageBox with this:
MessageBox.Show (Me, e.Message, "Error!")
End Try

End Sub -----------------------------------------
THE FOLLOWING SUB PROCESSES THE COMMANDS
-----------------------------------------
Public Sub ProcessCommands (ByVal strMessage As String)
'TMSG|123456789 0|Matt|12345678 90|Message
Dim dataArray() As String
Dim lstR As ListViewItem
dataArray = Split(strMessag e, Chr(124))
Select Case dataArray(0)
Case "RNICK"
'lstR = lstContacts.Ite ms.Add(dataArra y(2))
'lstR.SubItems. Add(dataArray(1 ))
-----------------------------------------
THIS IS THE PROBLEM AREA, IDEALLY IT WOULD BE GOOD TO HAVE THIS WHOLE
SUB RUNNING OUT OF THE THREAD SO I CAN EXECUTE CODE HERE
-----------------------------------------
Case "TMSG"
'open message window
'display received message
'Open a new window, or open window with tabs
If F4 Is Nothing Then
F4 = New frmMessage
F4.Show()
End If
Case "ERROR"
MsgBox(dataArra y(1), MsgBoxStyle.Exc lamation, "An Error
Has Occured")
As above: MessageBox.Show (Me, dataArray(1), "An Error has occurred",
MessageBoxButto ns.OK, _
MessageBoxIcon. Exclamation)
End Select
End Sub
-----------------------------------------


Hope this helps. Also, you might want to make some of your methods Private
instead of Public. Anything that doesn't need to be called from another
class should be Private.

--
Sven Groot
Nov 20 '05 #9
I think i have nearly got it the only thing is all my code is in its own
class e.g. the functions i have shown you exist in clsClient and i have
them defined on form using:

Public clsClient As New clsClient

I tried to put this into a class:

Me.Invoke(New ProcessCommands Delegate(Addres sOf ProcessCommands ), _
New Object() {strMessage})
I get an error saying that invoke is not a member of clsClient. What do
i do now, sorry i will get there and thank you very much for your help.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1451
by: Gonçalo Rodrigues | last post by:
Hi, I have a problem with threads and sockets. I'll try to describe the problem in words with pseudo-code. I've been working on a few classes to make it easier to work with threads. This framework, let us call it that, consists in two parts. The first part is just a basic thread class deriving from threading.Thread with a few extra functionality that makes it easier for a thread to spawn a new thread and "father it". Each of its
3
10404
by: Logan McKinley | last post by:
I have a C# program that uses blocking sockets and want to allow the user to stop the server. The problem I am having is the socket blocks on -------------------------------------------------------------- listener = new System.Net.Sockets.TcpListener(6254); listener.Start(); //skt is a socket skt =listener.AcceptSocket(); <--- this line blocks -------------------------------------------------------------- I attempt to stop the thread...
0
1304
by: Tressa | last post by:
Sorry to be such a novice about this but..... I have a windows service. It contains two separate files. Both have the same namespace name. I need to pass "bDisplay" into the other file. I am getting several errors and not sure why or how to solve them does anyone have any help? How do I access the other file? ServerSocket.cs *This is where the main server start is so the" private bool m_bIsDisplayed = false;" had to go here so it...
1
4542
by: hamil | last post by:
I am having trouble using the TcpListener and TcpClient classes. At the end of this post is server code that runs, and a class whose purpose is described below. I need to know when the client closes the connection so I can exit my listener code. Here is what I have tried. First I asked MSDN and they said..
5
1274
by: Jason L James | last post by:
Hi all, as a VB.Net programmer I am finding it difficult to find a text on implementing sockets to communicate with an embedded web server. Does anyone know of a good resource, either text book or on-line that I should refer to. I also need to implement multi-threading to enable me to communicate with several embedded devices at the same time.
0
996
by: Eternal Snow | last post by:
Hello. I have some trouble. Please look at this code below written in VB2005 (.net 2 50727). Sub Main() Dim osck As Net.Sockets.Socket Dim datagram() As Byte = {69, 0, 0, 52, 108, 180, 0, 0, 128, 6, 12, 4, 0, 0, 0, 1, 192, 168, 1, 99, 0, 80, 4, 180, 18, 28, 83, 142, 233, 81, 96, 210, 128, 18, 64, 0, 184, 41, 0, 0, 2, 4, 5, 180, 1, 3, 3, 0, 1, 1, 4, 2} osck = New
5
4774
by: zxo102 | last post by:
Hi, I am doing a small project using socket server and thread in python. This is first time for me to use socket and thread things. Here is my case. I have 20 socket clients. Each client send a set of sensor data per second to a socket server. The socket server will do two things: 1. write data into a file via bsddb; 2. forward the data to a GUI written in wxpython. I am thinking the code should work as follow (not sure it is feasible)...
0
1422
by: Rambaldi | last post by:
Hi there, I can connect to the WebMethod from the WM6 emulator, but i cant connect from the device :S Shouldnt the device work as fine as the Emulator??? I change the web reference url to my local machine but it does just make it work to the emulator. Why this is happening??? I got an apresentation like in 3/4 hours :S and i got to show the app in the device :S
0
9572
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2978
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.