473,394 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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.cs
private void ReadCallback(IAsyncResult ar)
{
string content = String.Empty;

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

// from the asynchronous state object.
StateObject state=(StateObject)ar.AsyncState;
Socket handler = state.workSocket;

// Read data from the client socket.
int bytesRead = handler.EndReceive(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.ToString();

// 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.Substring( 0 , 3 ) ==
"LOG" )
{
end_index = content.IndexOf(
"EOF", 4 );
if( end_index != -1 )
{
logonname =
content.Substring( start_index, end_index - start_index -1 );
this.mainform.listBox_user.Items.Add( logonname );
}

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

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

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

}
else if( content.Substring( 0 , 3 ) ==
"REF" )
{
}
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0, new AsyncCallback( ReadCallback ), state );
}
}
else
{
Clogging.log( mainform.listView_log, "Client
disconnected from ip " + this.IpAddress + " port number " +
((IPEndPoint)handler.RemoteEndPoint).Port.ToString () + " is now free"
, (int)MessageStatus.INFORMATION );

// disconnect serveren
this.CServer.DisconnectClient( 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.cs
private void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

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

// Create a TCP/IP socket.
listener = new Socket(
AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp );
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.listView_log, "Server started, binding to any ip this
machine have, listning on port " + this.PortNumber ,
(int)MessageStatus.INFORMATION );
}
else
{
Clogging.log(
this.mainform.listView_log, "Server started, binding to ip " +
this.IpAddress + " listning on port " + this.PortNumber ,
(int)MessageStatus.INFORMATION );
}

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

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

// Wait until a connection is
made before continuing.
ThreadSignal.WaitOne();
}
}
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.ServerRunning )
{
// Signal the main thread to
continue.
ThreadSignal.Set();

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

// object that will hold
usefull information
ClientObject clientObj = new
ClientObject();
clientObj.server = this;
clientObj.socket = handler;
clientObj.form = mainform;

// write to log
Clogging.log(
this.mainform.listView_log, "Client connected from ip " +
IPAddress.Parse (((IPEndPoint)handler.RemoteEndPoint).Address.ToSt ring
()) + " now talking on port number " +
((IPEndPoint)handler.RemoteEndPoint).Port.ToString (),
(int)MessageStatus.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 2853
Once the client closes the connection, the server should be looking for a
socket closed state.
"Rene Sørensen" <re**@deltadk.dk> wrote in message
news:l9********************************@4ax.com...
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.cs
private void ReadCallback(IAsyncResult ar)
{
string content = String.Empty;

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

// from the asynchronous state object.
StateObject state=(StateObject)ar.AsyncState;
Socket handler = state.workSocket;

// Read data from the client socket.
int bytesRead = handler.EndReceive(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.ToString();

// 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.Substring( 0 , 3 ) ==
"LOG" )
{
end_index = content.IndexOf(
"EOF", 4 );
if( end_index != -1 )
{
logonname =
content.Substring( start_index, end_index - start_index -1 );
this.mainform.listBox_user.Items.Add( logonname );
}

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

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

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

}
else if( content.Substring( 0 , 3 ) ==
"REF" )
{
}
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0, new AsyncCallback( ReadCallback ), state );
}
}
else
{
Clogging.log( mainform.listView_log, "Client
disconnected from ip " + this.IpAddress + " port number " +
((IPEndPoint)handler.RemoteEndPoint).Port.ToString () + " is now free"
, (int)MessageStatus.INFORMATION );

// disconnect serveren
this.CServer.DisconnectClient( 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.cs
private void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

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

// Create a TCP/IP socket.
listener = new Socket(
AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp );
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.listView_log, "Server started, binding to any ip this
machine have, listning on port " + this.PortNumber ,
(int)MessageStatus.INFORMATION );
}
else
{
Clogging.log(
this.mainform.listView_log, "Server started, binding to ip " +
this.IpAddress + " listning on port " + this.PortNumber ,
(int)MessageStatus.INFORMATION );
}

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

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

// Wait until a connection is
made before continuing.
ThreadSignal.WaitOne();
}
}
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.ServerRunning )
{
// Signal the main thread to
continue.
ThreadSignal.Set();

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

// object that will hold
usefull information
ClientObject clientObj = new
ClientObject();
clientObj.server = this;
clientObj.socket = handler;
clientObj.form = mainform;

// write to log
Clogging.log(
this.mainform.listView_log, "Client connected from ip " +
IPAddress.Parse (((IPEndPoint)handler.RemoteEndPoint).Address.ToSt ring
()) + " now talking on port number " +
((IPEndPoint)handler.RemoteEndPoint).Port.ToString (),
(int)MessageStatus.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.Sockets 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..jwaonline..com
-----------------------------------------------------------------------
"Richard T. Edwards" <r.*********@comcast.net> wrote in message news:i9********************@comcast.com...
Once the client closes the connection, the server should be looking for a socket closed state.
"Rene Sørensen" <re**@deltadk.dk> wrote in message news:l9********************************@4ax.com...
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.cs
private void ReadCallback(IAsyncResult ar)
{
string content = String.Empty;

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

// from the asynchronous state object.
StateObject state=(StateObject)ar.AsyncState;
Socket handler = state.workSocket;

// Read data from the client socket.
int bytesRead = handler.EndReceive(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.ToString();

// 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.Substring( 0 , 3 ) ==
"LOG" )
{
end_index = content.IndexOf(
"EOF", 4 );
if( end_index != -1 )
{
logonname =
content.Substring( start_index, end_index - start_index -1 );
this.mainform.listBox_user.Items.Add( logonname );
}

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

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

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

}
else if( content.Substring( 0 , 3 ) ==
"REF" )
{
}
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0, new AsyncCallback( ReadCallback ), state );
}
}
else
{
Clogging.log( mainform.listView_log, "Client
disconnected from ip " + this.IpAddress + " port number " +
((IPEndPoint)handler.RemoteEndPoint).Port.ToString () + " is now free"
, (int)MessageStatus.INFORMATION );

// disconnect serveren
this.CServer.DisconnectClient( 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.cs
private void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

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

// Create a TCP/IP socket.
listener = new Socket(
AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp );
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.listView_log, "Server started, binding to any ip this
machine have, listning on port " + this.PortNumber ,
(int)MessageStatus.INFORMATION );
}
else
{
Clogging.log(
this.mainform.listView_log, "Server started, binding to ip " +
this.IpAddress + " listning on port " + this.PortNumber ,
(int)MessageStatus.INFORMATION );
}

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

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

// Wait until a connection is
made before continuing.
ThreadSignal.WaitOne();
}
}
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.ServerRunning )
{
// Signal the main thread to
continue.
ThreadSignal.Set();

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

// object that will hold
usefull information
ClientObject clientObj = new
ClientObject();
clientObj.server = this;
clientObj.socket = handler;
clientObj.form = mainform;

// write to log
Clogging.log(
this.mainform.listView_log, "Client connected from ip " +
IPAddress.Parse (((IPEndPoint)handler.RemoteEndPoint).Address.ToSt ring
()) + " now talking on port number " +
((IPEndPoint)handler.RemoteEndPoint).Port.ToString (),
(int)MessageStatus.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
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...
4
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...
4
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...
4
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...

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.