473,685 Members | 2,800 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

socket problemswhos

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 where we use or game client, the difference between
them is that game client is sending a string when it connects. Our
problem is that when the telnet client close the connection, the
BeginRecive gets a -1, this is ok, when the game client close the
connection, nothing happens on the server nothing at all happens. I
have no ide where to look or where to begine here, but for at start
the code for begineread and the start server code is below here. We
real need a hand here, thanks

JORM Team

Code from CSocketClient.c s
private void ReadCallback(IA syncResult ar)
{
string content = String.Empty;

try
{
// Retrieve the state object and the
handler socket

// from the asynchronous state object.
StateObject state=(StateObj ect)ar.AsyncSta te;
Socket handler = state.workSocke t;

// Read data from the client socket.
int bytesRead = handler.EndRece ive(ar);

if ( bytesRead > 0 )
{
// There might be more data, so store the
data received so far.
state.sb.Append (Encoding.UTF8. GetString(
state.buffer , 0 , bytesRead ) );

// Check for end-of-file tag. If it is not
there, read
// more data.
content = state.sb.ToStri ng();

// is end og file reached
if ( content.IndexOf ("EOF") > -1 )
{
int start_index = 4;
int end_index = 0;

// Echo the data back to the client.
//this.Send( handler, content );
if( content.Substri ng( 0 , 3 ) ==
"LOG" )
{
end_index = content.IndexOf (
"EOF", 4 );
if( end_index != -1 )
{
logonname =
content.Substri ng( start_index, end_index - start_index -1 );
this.mainform.l istBox_user.Ite ms.Add( logonname );
}

}
else if( content.Substri ng( 0 , 3 ) ==
"OBR" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"JOI" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"SET" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"REF" )
{
}
}
else
{
// Not all data received. Get more.
handler.BeginRe ceive(state.buf fer, 0,
StateObject.Buf ferSize, 0, new AsyncCallback( ReadCallback ), state );
}
}
else
{
Clogging.log( mainform.listVi ew_log, "Client
disconnected from ip " + this.IpAddress + " port number " +
((IPEndPoint)ha ndler.RemoteEnd Point).Port.ToS tring() + " is now free"
, (int)MessageSta tus.INFORMATION );

// disconnect serveren
this.CServer.Di sconnectClient( this );
}
}
catch( SocketException ex )
{
error( "Socket Error Message:\n" + ex.Message + "
\n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Unknown Error Message:\n" + ex.Message + "
\n\n" + ex.StackTrace );
}
}

Code from CSocketServer.c s
private void StartListening( )
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the
socket.
IPEndPoint localEndPoint = new
IPEndPoint(IPAd dress.Any, iPort );

// Create a TCP/IP socket.
listener = new Socket(
AddressFamily.I nterNetwork , SocketType.Stre am, ProtocolType.Tc p );
try
{
// Bind the socket to the local
endpoint and listen for incoming connections.
listener.Bind( localEndPoint );

//accept this a amount of connection
listener.Listen ( 15 );

// NOTIC
// stupid test, have to find a smarter
way
if( this.IpAddress == "0.0.0.0" )
{
Clogging.log(
this.mainform.l istView_log, "Server started, binding to any ip this
machine have, listning on port " + this.PortNumber ,
(int)MessageSta tus.INFORMATION );
}
else
{
Clogging.log(
this.mainform.l istView_log, "Server started, binding to ip " +
this.IpAddress + " listning on port " + this.PortNumber ,
(int)MessageSta tus.INFORMATION );
}

while( ServerRunning )
{
// Set the event to
nonsignaled state.
ThreadSignal.Re set();

// wating for
listener.BeginA ccept( new
AsyncCallback( AcceptCallback ), listener );

// Wait until a connection is
made before continuing.
ThreadSignal.Wa itOne();
}
}
catch( SocketException ex )
{
error("Error Message:\n" + ex.Message
+ " \n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Error Message:\n" + ex.Message
+ " \n\n" + ex.StackTrace );
}
}

/// <summary>
///
/// </summary>
/// <param name="ar"></param>
private void AcceptCallback( IAsyncResult ar)
{
try
{
// a funny this is, when the listen
socket get a close
// this function is called againe, i
use this test to make
// sure, no NullRefrence is used
if( this.ServerRunn ing )
{
// Signal the main thread to
continue.
ThreadSignal.Se t();

// Get the socket that handles
the client request.
Socket listener = (Socket)
ar.AsyncState;
Socket handler =
listener.EndAcc ept(ar);

// object that will hold
usefull information
ClientObject clientObj = new
ClientObject();
clientObj.serve r = this;
clientObj.socke t = handler;
clientObj.form = mainform;

// write to log
Clogging.log(
this.mainform.l istView_log, "Client connected from ip " +
IPAddress.Parse (((IPEndPoint)h andler.RemoteEn dPoint).Address .ToString
()) + " now talking on port number " +
((IPEndPoint)ha ndler.RemoteEnd Point).Port.ToS tring(),
(int)MessageSta tus.INFORMATION );

client = new CSocketClient(
clientObj );

// add a client to our client
list
clientList.Add( client );
}
}
catch( SocketException ex )
{
error( "Socket Error Message:\n" +
ex.Message + " \n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Unknown Error Message:\n" +
ex.Message + " \n\n" + ex.StackTrace );
}
}
Nov 17 '05 #1
2 2873
Once the client closes the connection, the server should be looking for a
socket closed state.
"Rene Sørensen" <re**@deltadk.d k> wrote in message
news:l9******** *************** *********@4ax.c om...
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 where we use or game client, the difference between
them is that game client is sending a string when it connects. Our
problem is that when the telnet client close the connection, the
BeginRecive gets a -1, this is ok, when the game client close the
connection, nothing happens on the server nothing at all happens. I
have no ide where to look or where to begine here, but for at start
the code for begineread and the start server code is below here. We
real need a hand here, thanks

JORM Team

Code from CSocketClient.c s
private void ReadCallback(IA syncResult ar)
{
string content = String.Empty;

try
{
// Retrieve the state object and the
handler socket

// from the asynchronous state object.
StateObject state=(StateObj ect)ar.AsyncSta te;
Socket handler = state.workSocke t;

// Read data from the client socket.
int bytesRead = handler.EndRece ive(ar);

if ( bytesRead > 0 )
{
// There might be more data, so store the
data received so far.
state.sb.Append (Encoding.UTF8. GetString(
state.buffer , 0 , bytesRead ) );

// Check for end-of-file tag. If it is not
there, read
// more data.
content = state.sb.ToStri ng();

// is end og file reached
if ( content.IndexOf ("EOF") > -1 )
{
int start_index = 4;
int end_index = 0;

// Echo the data back to the client.
//this.Send( handler, content );
if( content.Substri ng( 0 , 3 ) ==
"LOG" )
{
end_index = content.IndexOf (
"EOF", 4 );
if( end_index != -1 )
{
logonname =
content.Substri ng( start_index, end_index - start_index -1 );
this.mainform.l istBox_user.Ite ms.Add( logonname );
}

}
else if( content.Substri ng( 0 , 3 ) ==
"OBR" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"JOI" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"SET" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"REF" )
{
}
}
else
{
// Not all data received. Get more.
handler.BeginRe ceive(state.buf fer, 0,
StateObject.Buf ferSize, 0, new AsyncCallback( ReadCallback ), state );
}
}
else
{
Clogging.log( mainform.listVi ew_log, "Client
disconnected from ip " + this.IpAddress + " port number " +
((IPEndPoint)ha ndler.RemoteEnd Point).Port.ToS tring() + " is now free"
, (int)MessageSta tus.INFORMATION );

// disconnect serveren
this.CServer.Di sconnectClient( this );
}
}
catch( SocketException ex )
{
error( "Socket Error Message:\n" + ex.Message + "
\n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Unknown Error Message:\n" + ex.Message + "
\n\n" + ex.StackTrace );
}
}

Code from CSocketServer.c s
private void StartListening( )
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the
socket.
IPEndPoint localEndPoint = new
IPEndPoint(IPAd dress.Any, iPort );

// Create a TCP/IP socket.
listener = new Socket(
AddressFamily.I nterNetwork , SocketType.Stre am, ProtocolType.Tc p );
try
{
// Bind the socket to the local
endpoint and listen for incoming connections.
listener.Bind( localEndPoint );

//accept this a amount of connection
listener.Listen ( 15 );

// NOTIC
// stupid test, have to find a smarter
way
if( this.IpAddress == "0.0.0.0" )
{
Clogging.log(
this.mainform.l istView_log, "Server started, binding to any ip this
machine have, listning on port " + this.PortNumber ,
(int)MessageSta tus.INFORMATION );
}
else
{
Clogging.log(
this.mainform.l istView_log, "Server started, binding to ip " +
this.IpAddress + " listning on port " + this.PortNumber ,
(int)MessageSta tus.INFORMATION );
}

while( ServerRunning )
{
// Set the event to
nonsignaled state.
ThreadSignal.Re set();

// wating for
listener.BeginA ccept( new
AsyncCallback( AcceptCallback ), listener );

// Wait until a connection is
made before continuing.
ThreadSignal.Wa itOne();
}
}
catch( SocketException ex )
{
error("Error Message:\n" + ex.Message
+ " \n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Error Message:\n" + ex.Message
+ " \n\n" + ex.StackTrace );
}
}

/// <summary>
///
/// </summary>
/// <param name="ar"></param>
private void AcceptCallback( IAsyncResult ar)
{
try
{
// a funny this is, when the listen
socket get a close
// this function is called againe, i
use this test to make
// sure, no NullRefrence is used
if( this.ServerRunn ing )
{
// Signal the main thread to
continue.
ThreadSignal.Se t();

// Get the socket that handles
the client request.
Socket listener = (Socket)
ar.AsyncState;
Socket handler =
listener.EndAcc ept(ar);

// object that will hold
usefull information
ClientObject clientObj = new
ClientObject();
clientObj.serve r = this;
clientObj.socke t = handler;
clientObj.form = mainform;

// write to log
Clogging.log(
this.mainform.l istView_log, "Client connected from ip " +
IPAddress.Parse (((IPEndPoint)h andler.RemoteEn dPoint).Address .ToString
()) + " now talking on port number " +
((IPEndPoint)ha ndler.RemoteEnd Point).Port.ToS tring(),
(int)MessageSta tus.INFORMATION );

client = new CSocketClient(
clientObj );

// add a client to our client
list
clientList.Add( client );
}
}
catch( SocketException ex )
{
error( "Socket Error Message:\n" +
ex.Message + " \n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Unknown Error Message:\n" +
ex.Message + " \n\n" + ex.StackTrace );
}
}

Nov 17 '05 #2
Take a look at TcpClient and TcpListener (or UdpClient and UdpListener if that's what you're using). They can be used to simplify
some of the tasks of writing a protocol server and/or client, although they provide the transport and protocols but not any built-in
communication. They are in the System.Net.Sock ets namespace.

It seems like you're after a graceful shutdown of the client socket. I suspect that the telnet client would behave exactly as a
custom client from the point of view of a server socket. You can either Socket.Poll periodically on the server (or indefinately in
a loop on another thread) to check for invalid sockets or implement the Dispose pattern in your client so that it always has a
chance to notify the server that it's disconnecting.

If it wasn't for the telnet requirement I'd just recommend using Remoting to simplify the rest of this stuff, although, you could
probably do this using remoting for the "game client" and create a special telnet server interface on the side that marshals calls
to your remoting infrastructure. This would require different ports for the two different clients, however.

Hope it helps.

--
Dave Sexton
dave@www..jwaon line..com
-----------------------------------------------------------------------
"Richard T. Edwards" <r.*********@co mcast.net> wrote in message news:i9******** ************@co mcast.com...
Once the client closes the connection, the server should be looking for a socket closed state.
"Rene Sørensen" <re**@deltadk.d k> wrote in message news:l9******** *************** *********@4ax.c om...
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 where we use or game client, the difference between
them is that game client is sending a string when it connects. Our
problem is that when the telnet client close the connection, the
BeginRecive gets a -1, this is ok, when the game client close the
connection, nothing happens on the server nothing at all happens. I
have no ide where to look or where to begine here, but for at start
the code for begineread and the start server code is below here. We
real need a hand here, thanks

JORM Team

Code from CSocketClient.c s
private void ReadCallback(IA syncResult ar)
{
string content = String.Empty;

try
{
// Retrieve the state object and the
handler socket

// from the asynchronous state object.
StateObject state=(StateObj ect)ar.AsyncSta te;
Socket handler = state.workSocke t;

// Read data from the client socket.
int bytesRead = handler.EndRece ive(ar);

if ( bytesRead > 0 )
{
// There might be more data, so store the
data received so far.
state.sb.Append (Encoding.UTF8. GetString(
state.buffer , 0 , bytesRead ) );

// Check for end-of-file tag. If it is not
there, read
// more data.
content = state.sb.ToStri ng();

// is end og file reached
if ( content.IndexOf ("EOF") > -1 )
{
int start_index = 4;
int end_index = 0;

// Echo the data back to the client.
//this.Send( handler, content );
if( content.Substri ng( 0 , 3 ) ==
"LOG" )
{
end_index = content.IndexOf (
"EOF", 4 );
if( end_index != -1 )
{
logonname =
content.Substri ng( start_index, end_index - start_index -1 );
this.mainform.l istBox_user.Ite ms.Add( logonname );
}

}
else if( content.Substri ng( 0 , 3 ) ==
"OBR" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"JOI" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"SET" )
{

}
else if( content.Substri ng( 0 , 3 ) ==
"REF" )
{
}
}
else
{
// Not all data received. Get more.
handler.BeginRe ceive(state.buf fer, 0,
StateObject.Buf ferSize, 0, new AsyncCallback( ReadCallback ), state );
}
}
else
{
Clogging.log( mainform.listVi ew_log, "Client
disconnected from ip " + this.IpAddress + " port number " +
((IPEndPoint)ha ndler.RemoteEnd Point).Port.ToS tring() + " is now free"
, (int)MessageSta tus.INFORMATION );

// disconnect serveren
this.CServer.Di sconnectClient( this );
}
}
catch( SocketException ex )
{
error( "Socket Error Message:\n" + ex.Message + "
\n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Unknown Error Message:\n" + ex.Message + "
\n\n" + ex.StackTrace );
}
}

Code from CSocketServer.c s
private void StartListening( )
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the
socket.
IPEndPoint localEndPoint = new
IPEndPoint(IPAd dress.Any, iPort );

// Create a TCP/IP socket.
listener = new Socket(
AddressFamily.I nterNetwork , SocketType.Stre am, ProtocolType.Tc p );
try
{
// Bind the socket to the local
endpoint and listen for incoming connections.
listener.Bind( localEndPoint );

//accept this a amount of connection
listener.Listen ( 15 );

// NOTIC
// stupid test, have to find a smarter
way
if( this.IpAddress == "0.0.0.0" )
{
Clogging.log(
this.mainform.l istView_log, "Server started, binding to any ip this
machine have, listning on port " + this.PortNumber ,
(int)MessageSta tus.INFORMATION );
}
else
{
Clogging.log(
this.mainform.l istView_log, "Server started, binding to ip " +
this.IpAddress + " listning on port " + this.PortNumber ,
(int)MessageSta tus.INFORMATION );
}

while( ServerRunning )
{
// Set the event to
nonsignaled state.
ThreadSignal.Re set();

// wating for
listener.BeginA ccept( new
AsyncCallback( AcceptCallback ), listener );

// Wait until a connection is
made before continuing.
ThreadSignal.Wa itOne();
}
}
catch( SocketException ex )
{
error("Error Message:\n" + ex.Message
+ " \n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Error Message:\n" + ex.Message
+ " \n\n" + ex.StackTrace );
}
}

/// <summary>
///
/// </summary>
/// <param name="ar"></param>
private void AcceptCallback( IAsyncResult ar)
{
try
{
// a funny this is, when the listen
socket get a close
// this function is called againe, i
use this test to make
// sure, no NullRefrence is used
if( this.ServerRunn ing )
{
// Signal the main thread to
continue.
ThreadSignal.Se t();

// Get the socket that handles
the client request.
Socket listener = (Socket)
ar.AsyncState;
Socket handler =
listener.EndAcc ept(ar);

// object that will hold
usefull information
ClientObject clientObj = new
ClientObject();
clientObj.serve r = this;
clientObj.socke t = handler;
clientObj.form = mainform;

// write to log
Clogging.log(
this.mainform.l istView_log, "Client connected from ip " +
IPAddress.Parse (((IPEndPoint)h andler.RemoteEn dPoint).Address .ToString
()) + " now talking on port number " +
((IPEndPoint)ha ndler.RemoteEnd Point).Port.ToS tring(),
(int)MessageSta tus.INFORMATION );

client = new CSocketClient(
clientObj );

// add a client to our client
list
clientList.Add( client );
}
}
catch( SocketException ex )
{
error( "Socket Error Message:\n" +
ex.Message + " \n\n" + ex.StackTrace );
}
catch( Exception ex )
{
error( "Unknown Error Message:\n" +
ex.Message + " \n\n" + ex.StackTrace );
}
}


Nov 17 '05 #3

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

Similar topics

8
9278
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):
4
8724
by: DreJoh | last post by:
I've read many articles on the subject and the majority of them give the same solution that's in article 821625 on the MSDN website. I'm using the following code and when a the client disconnects the child socket remains in the CLOSE_WAIT state. Anyone have any idea what's missing? ----------------------------- Socket Code ----------------------------- namespace Sockets { #region Class - SocketClient
4
18115
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.
4
1483
by: DreJoh | last post by:
I've read many articles on the subject and the majority of them give the same solution that's in article 821625 on the MSDN website. I'm using the following code and when a the client disconnects the child socket remains in the CLOSE_WAIT state. Anyone have any idea what's missing? ----------------------------- Socket Code ----------------------------- namespace Sockets { #region Class - SocketClient
0
8926
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
8761
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
8773
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
7589
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
5792
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
4302
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
4523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1927
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.