R
Rene Sørensen
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.ToString
()) + " 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 );
}
}
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.ToString
()) + " 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 );
}
}