473,624 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

multithread c# socket server

Hello:

I write a multithread c# socket server,it is a winform application,the re is
a richtextbox control and button,when the button is click,the server begin
to listen the socket port,waiting for a incoming connection,the relative
code snipprt as following::

private IPAddress myIP=IPAddress. Parse("127.0.0. 1");

private IPEndPoint myServer;

private Socket socket;

private Socket accSocket;

private System.Windows. Forms.Button button2;

private bool check;

private void button1_Click(o bject sender, System.EventArg s e)

{

check=true;

try

{

Thread thread =new Thread(new ThreadStart(acc p));

thread.Start();

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}

private void accp()

{

myServer=new IPEndPoint(myIP ,Int32.Parse("2 0000"));

socket=new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

socket.Bind(myS erver);

socket.Listen(5 0);

while(true)

{

try

{

accSocket=socke t.Accept();

if(accSocket.Co nnected)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

}

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}

}

private void round()

{

Byte[] rec=new Byte[1024];

NetworkStream acceptStream=ne w NetworkStream(a ccSocket);

int i=0;

while((i=accept Stream.Read(rec ,0,rec.Length)) !=0)

{

string
recMessage=Syst em.Text.Encodin g.Default.GetSt ring(rec);

rec=new Byte[1024];

this.richTextBo x1.AppendText(r ecMessage);

}

}

¡*¡*¡*¡*¡*¡*¡*¡ *¡*¡*¡*¡*¡*¡*¡* .

¡*¡*¡*¡*¡*¡*¡*¡ *¡*¡*¡*¡*¡*¡*¡*



In order to test the server,I write a multithread client too,there is only
one button in the form,when it is clicked,four threads is generated to
connect the server simultaneously, each thread write one line to the server
socket.code as:



private IPAddress myIP;

private IPEndPoint myServer;

private Socket socket;

private void button1_Click(o bject sender, System.EventArg s e)

{

for(int i=0;i<4;i++)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

thread.Join();

}

}

private void round()

{

try

{

myIP=IPAddress. Parse("127.0.0. 1");

myServer=new IPEndPoint(myIP ,Int32.Parse("2 0000"));

socket=new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

socket.Connect( myServer);

NetworkStream netStream=new NetworkStream(s ocket);

Byte[] byteMessage=new Byte[640];

string sendMessage="´ó ¼ÒºÃ£¡£¡£¡£¡!\r \n";
byteMessage=Sys tem.Text.Encodi ng.Default.GetB ytes(sendMessag e.ToCharArray() )
;

// socket.Send(byt eMessage,byteMe ssage.Length,0) ;

netStream.Write (byteMessage,0, byteMessage.Len gth);

netStream.Flush ();

netStream.Close ();

socket.Close();

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}



As you can see,when I click the button in the client side,I should see four
lines is printed in the server side.but in fact,I can¡¯t,I can only see one
line,sometimes two or three lines,by my tracing,I found they always come
from the last several threads.if I modify the button click event in the
client as following(add sleep between the threads),it works well,that is I
can see four lines every time in the server:

private void button1_Click(o bject sender, System.EventArg s e)

{

for(int i=0;i<4;i++)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

thread.Join();

Thread.Sleep(10 0);

}

}

If I modify the timeout param of the sleep method to lower and lower, the
mentioned problem occur again.i also write a java multithread server, it
works well to the simuteneous thread connection.

Why c# socket server can¡¯t handle the simultaneous access?is it a bug?by
comparing the java server and c# server,I also found that the java server is
faster then c# server.

Any instruction?Tha nk you.


Nov 16 '05 #1
2 26498
You do not have to repost you message over and over. As far as I see 6
messages from now you recieved an answer from community member, Henrik Dahl,
to your question. So why repost? Use the current thread to continue
conversation if needed...

Sorry for this,

--
Tamir Khason
You want dot.NET? Just ask:
"Please, www.dotnet.us "
"zhebincong " <co********@cap info.com.cn> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
Hello:

I write a multithread c# socket server,it is a winform application,the re is a richtextbox control and button,when the button is click,the server begin
to listen the socket port,waiting for a incoming connection,the relative
code snipprt as following::

private IPAddress myIP=IPAddress. Parse("127.0.0. 1");

private IPEndPoint myServer;

private Socket socket;

private Socket accSocket;

private System.Windows. Forms.Button button2;

private bool check;

private void button1_Click(o bject sender, System.EventArg s e)

{

check=true;

try

{

Thread thread =new Thread(new ThreadStart(acc p));

thread.Start();

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}

private void accp()

{

myServer=new IPEndPoint(myIP ,Int32.Parse("2 0000"));

socket=new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

socket.Bind(myS erver);

socket.Listen(5 0);

while(true)

{

try

{

accSocket=socke t.Accept();

if(accSocket.Co nnected)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

}

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}

}

private void round()

{

Byte[] rec=new Byte[1024];

NetworkStream acceptStream=ne w NetworkStream(a ccSocket);

int i=0;

while((i=accept Stream.Read(rec ,0,rec.Length)) !=0)

{

string
recMessage=Syst em.Text.Encodin g.Default.GetSt ring(rec);

rec=new Byte[1024];

this.richTextBo x1.AppendText(r ecMessage);

}

}

¡*¡*¡*¡*¡*¡*¡*¡ *¡*¡*¡*¡*¡*¡*¡* .

¡*¡*¡*¡*¡*¡*¡*¡ *¡*¡*¡*¡*¡*¡*¡*



In order to test the server,I write a multithread client too,there is only
one button in the form,when it is clicked,four threads is generated to
connect the server simultaneously, each thread write one line to the server
socket.code as:



private IPAddress myIP;

private IPEndPoint myServer;

private Socket socket;

private void button1_Click(o bject sender, System.EventArg s e)

{

for(int i=0;i<4;i++)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

thread.Join();

}

}

private void round()

{

try

{

myIP=IPAddress. Parse("127.0.0. 1");

myServer=new IPEndPoint(myIP ,Int32.Parse("2 0000"));

socket=new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

socket.Connect( myServer);

NetworkStream netStream=new NetworkStream(s ocket);

Byte[] byteMessage=new Byte[640];

string sendMessage="´ó ¼ÒºÃ£¡£¡£¡£¡!\r \n";
byteMessage=Sys tem.Text.Encodi ng.Default.GetB ytes(sendMessag e.ToCharArray() ) ;

// socket.Send(byt eMessage,byteMe ssage.Length,0) ;

netStream.Write (byteMessage,0, byteMessage.Len gth);

netStream.Flush ();

netStream.Close ();

socket.Close();

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}



As you can see,when I click the button in the client side,I should see four lines is printed in the server side.but in fact,I can¡¯t,I can only see one line,sometimes two or three lines,by my tracing,I found they always come
from the last several threads.if I modify the button click event in the
client as following(add sleep between the threads),it works well,that is I
can see four lines every time in the server:

private void button1_Click(o bject sender, System.EventArg s e)

{

for(int i=0;i<4;i++)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

thread.Join();

Thread.Sleep(10 0);

}

}

If I modify the timeout param of the sleep method to lower and lower, the
mentioned problem occur again.i also write a java multithread server, it
works well to the simuteneous thread connection.

Why c# socket server can¡¯t handle the simultaneous access?is it a bug?by
comparing the java server and c# server,I also found that the java server is faster then c# server.

Any instruction?Tha nk you.

Nov 16 '05 #2
sorry,the other questions is posted from other forums,maybe microsoft community and several others ,and i only post one time in every forum.i don't know why they come here,maybe you are the same forum.



"Tamir Khason" wrote:
You do not have to repost you message over and over. As far as I see 6
messages from now you recieved an answer from community member, Henrik Dahl,
to your question. So why repost? Use the current thread to continue
conversation if needed...

Sorry for this,

--
Tamir Khason
You want dot.NET? Just ask:
"Please, www.dotnet.us "
"zhebincong " <co********@cap info.com.cn> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
Hello:

I write a multithread c# socket server,it is a winform application,the re

is
a richtextbox control and button,when the button is click,the server begin
to listen the socket port,waiting for a incoming connection,the relative
code snipprt as following::

private IPAddress myIP=IPAddress. Parse("127.0.0. 1");

private IPEndPoint myServer;

private Socket socket;

private Socket accSocket;

private System.Windows. Forms.Button button2;

private bool check;

private void button1_Click(o bject sender, System.EventArg s e)

{

check=true;

try

{

Thread thread =new Thread(new ThreadStart(acc p));

thread.Start();

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}

private void accp()

{

myServer=new IPEndPoint(myIP ,Int32.Parse("2 0000"));

socket=new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

socket.Bind(myS erver);

socket.Listen(5 0);

while(true)

{

try

{

accSocket=socke t.Accept();

if(accSocket.Co nnected)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

}

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}

}

private void round()

{

Byte[] rec=new Byte[1024];

NetworkStream acceptStream=ne w NetworkStream(a ccSocket);

int i=0;

while((i=accept Stream.Read(rec ,0,rec.Length)) !=0)

{

string
recMessage=Syst em.Text.Encodin g.Default.GetSt ring(rec);

rec=new Byte[1024];

this.richTextBo x1.AppendText(r ecMessage);

}

}

¡Â*¡Â*¡Â*¡ *¡Â*¡Â*¡Â*¡ Â*¡Â*¡Â*¡Â* ¡Â*¡Â*¡Â*¡Â* .

¡Â*¡Â*¡Â*¡ *¡Â*¡Â*¡Â*¡ Â*¡Â*¡Â*¡Â* ¡Â*¡Â*¡Â*¡Â*



In order to test the server,I write a multithread client too,there is only
one button in the form,when it is clicked,four threads is generated to
connect the server simultaneously, each thread write one line to the server
socket.code as:



private IPAddress myIP;

private IPEndPoint myServer;

private Socket socket;

private void button1_Click(o bject sender, System.EventArg s e)

{

for(int i=0;i<4;i++)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

thread.Join();

}

}

private void round()

{

try

{

myIP=IPAddress. Parse("127.0.0. 1");

myServer=new IPEndPoint(myIP ,Int32.Parse("2 0000"));

socket=new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

socket.Connect( myServer);

NetworkStream netStream=new NetworkStream(s ocket);

Byte[] byteMessage=new Byte[640];

string sendMessage="´ ó¼ÒºÃ£¡ £Â¡Â£Â¡Â£Â¡!\r\ n";

byteMessage=Sys tem.Text.Encodi ng.Default.GetB ytes(sendMessag e.ToCharArray() )
;

// socket.Send(byt eMessage,byteMe ssage.Length,0) ;

netStream.Write (byteMessage,0, byteMessage.Len gth);

netStream.Flush ();

netStream.Close ();

socket.Close();

}

catch(Exception ee)

{

MessageBox.Show (ee.Message);

}

}



As you can see,when I click the button in the client side,I should see

four
lines is printed in the server side.but in fact,I can¡¯t,I can only see

one
line,sometimes two or three lines,by my tracing,I found they always come
from the last several threads.if I modify the button click event in the
client as following(add sleep between the threads),it works well,that is I
can see four lines every time in the server:

private void button1_Click(o bject sender, System.EventArg s e)

{

for(int i=0;i<4;i++)

{

Thread thread=new Thread(new ThreadStart(rou nd));

thread.Start();

thread.Join();

Thread.Sleep(10 0);

}

}

If I modify the timeout param of the sleep method to lower and lower, the
mentioned problem occur again.i also write a java multithread server, it
works well to the simuteneous thread connection.

Why c# socket server can¡¯t handle the simultaneous access?is it a bug?by
comparing the java server and c# server,I also found that the java server

is
faster then c# server.

Any instruction?Tha nk you.


Nov 16 '05 #3

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

Similar topics

8
9276
by: simon place | last post by:
Spent some very frustrating hours recoding to find a way of closing a server socket, i'd not thought it would be any problem, however, after complete failure and as a last resort, i looked at the python wrapper module for sockets, and found that the close command doesn't actually call the underlying close! this didn't seem right, so i added it, and my code now works simply and as expected. def close(self):
0
1853
by: r_obert | last post by:
Hello, I'm trying to create a worker thread for my VC++ program, and was wondering whether I should be linking with the Multithread /MT or Multithread DLL /MD option? I'm not quite sure, in layman's terms, what the difference is. When I build with Multithread DLL, the linker complains about not being able to find a bunch of "unresolved external symbols" associated with nafxcwd.lib.
4
7077
by: zbcong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting for a incoming connection,the relative code snipprt as following:: private IPAddress myIP=IPAddress.Parse("127.0.0.1"); private IPEndPoint myServer; private Socket socket; private Socket accSocket; private System.Windows.Forms.Button button2;...
4
18108
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed as I find appropriate. I am using the socket asynchronously by calling the BeingSend and BeginReceive calls. I would like to be able to call shutdown and close asynchronously if possible.
2
2870
by: Rene Sørensen | last post by:
We are 4 students working on a assignment, that our teacher gave use, normally we do this is C++, but the 4 of us, use C# more often that C++ so… We made a small games called reversi, now our job is to make a server, none of us know nothing about socket programming in C#, but we founds some guides for this, and now ,got a server running, but we have some problems though. We have 2 scenario, one where we use a telnet connection and one...
4
2200
by: Crirus | last post by:
hello I need a sample of a server with multithreading accept connections with sockets... Have anyone? Thanks, Crirus
4
3598
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket client and asynchronous socket server example code provided in the .NET framework developers guide is a great start but I have not dealt with sockets before and I am struggling with something. From what I can tell the sample server code ...
1
7155
by: keksy | last post by:
Hi every1, I am writing a small client/server application and in it I want to send an image asynchronous from the client to the server through a TCP socket. I found an example code on the MSDN site, which is actually for sending strings. I tried to adapt this code so that the client sends an image instead of a string. However, there is something wrong on the server side (i guess)... The server starts listening, the client starts sending...
0
8672
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8330
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
8471
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
7153
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...
1
6107
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
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
4075
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
4167
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1474
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.