没写完的一个server,可以参考一下:using System; using System.Threading; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; using System.Text;namespace Server { /// <summary> /// Summary description for Class1. /// </summary> class DEServerListener { protected Socket _socListener = null; protected ArrayList _clientHandlers = new ArrayList(); protected int _workID = -1; protected IPAddress [] _aryLocalAddr = null; protected int _ipPort = 0; public DEServerListener(int ipPort) { string _strHostName = ""; _ipPort = ipPort; try { _strHostName = Dns.GetHostName(); IPHostEntry _ipEntry = Dns.GetHostByName( _strHostName ); _aryLocalAddr = _ipEntry.AddressList; } catch( Exception e ) { throw new Exception("Error trying to get local address."+ e.Message ); } if( _aryLocalAddr == null || _aryLocalAddr.Length < 1 ) { throw new Exception( "Unable to get local address" ); } _socListener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); _socListener.Bind( new IPEndPoint( _aryLocalAddr[0], ipPort ) ); //_socListener.Bind( new IPEndPoint( IPAddress.Loopback, _iPort ) ); // For use with localhost 127.0.0.1 _socListener.Listen(100); // Setup a callback to be notified of connection requests _socListener.BeginAccept( new AsyncCallback(OnConnectRequest ), _socListener ); } ~DEServerListener() { GC.Collect(); GC.WaitForPendingFinalizers(); } public void OnConnectRequest( IAsyncResult ar ) {
public bool isAvailable { get { return _isBusy; } } public ClientHandler(Socket client) { _isBusy = false; _socClient = client; clientTread = new Thread (new ThreadStart (ClientSession)); // SetupRecieveCallback(_socClient); } public void run(Socket client) { _isBusy = true; if(client.Connected) { _socClient=client; SetupRecieveCallback( _socClient ); } if (clientTread.ThreadState == ThreadState.Unstarted ) { clientTread.Start(); } if (clientTread.ThreadState == ThreadState.Suspended) { clientTread.Resume(); } if (clientTread.ThreadState == ThreadState.Stopped ) { clientTread = new Thread (new ThreadStart (ClientSession)); clientTread.Start(); } } private void ClientSession() { while(true) { DateTime now = DateTime.Now; String strDateLine = "Welcome " + now.ToString("G") + "\n\r"; // Convert to byte array and send. Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes( strDateLine.ToCharArray() ); if(_socClient.Connected) { _socClient.Send( byteDateLine, byteDateLine.Length, 0 ); Console.WriteLine("Connected"); } clientTread.Suspend(); } } public void SetupRecieveCallback( Socket sock ) { try { AsyncCallback recieveData = new AsyncCallback( OnRecievedData ); sock.BeginReceive( _bufferData, 0, _bufferData.Length , SocketFlags.None, recieveData, sock ); } catch( Exception e ) { Console.WriteLine(" Setup Recieve Callback failed! " + e.Message ); } } public void OnRecievedData( IAsyncResult ar ) { byte [] aryRet = GetRecievedData( ar ); // If no data was recieved then the connection is probably dead if( aryRet.Length < 1 ) { Console.WriteLine( "Client disconnected" ); _socClient.Close(); _isBusy = false; return; } try { //process data here Console.WriteLine(Encoding.ASCII.GetString(aryRet)); //end session if client send "stop" if(Encoding.ASCII.GetString(aryRet,0,4)=="stop") { Byte[] byteClose = Encoding.ASCII.GetBytes("bye"); _socClient.Send( byteClose, byteClose.Length, 0 ); _isBusy = false; _socClient.Close(); Console.WriteLine( "Client disconnected" ); } else { SetupRecieveCallback( _socClient ); } } catch { // If the send fails the close the connection Console.WriteLine( "Send to client {0} failed" ); _socClient.Close(); return; } } /// <summary> /// Data has been recieved so we shall put it in an array and /// return it. /// </summary> /// <param name="ar"></param> /// <returns>Array of bytes containing the received data</returns> private byte [] GetRecievedData( IAsyncResult ar ) { int nBytesRec = 0; try { nBytesRec = _socClient.EndReceive(ar); } catch{} byte [] byReturn = new byte[nBytesRec]; Array.Copy( _bufferData, byReturn, nBytesRec );
// Check for any remaining data and display it // This will improve performance for large packets // but adds nothing to readability and is not essential int nToBeRead = _socClient.Available; if( nToBeRead > 0 ) { byte [] byData = new byte[nToBeRead]; _socClient.Receive( byData ); // Append byData to byReturn here byte [] byReturnMore = new byte[byReturn.Length + byData.Length]; Array.Copy(byReturn,byReturnMore,byReturn.Length); Array.Copy(byData,0,byReturnMore,byReturn.Length ,byData.Length); return byReturnMore; } return byReturn; } } } class ServerStartup { static void Main(string[] args) { try { Console.WriteLine("Starting Server....."); DEServerListener _DEServerListener = new DEServerListener(399); Console.WriteLine("Server started, waiting for connections...."); } catch(Exception e) { Console.WriteLine("Server Start Error: {0}",e.Message ); } Console.ReadLine(); }
if(Login.Connected)
{
Byte[] sendArray=new Byte[64];
string msg;
//在数据表中循环每条记录发送一次
for(int i=0;i<this.dSetMember1.Tables[0].Rows.Count;i++)
{
msg=this.dSetMember1.Tables[0].Rows[i][1]+"@"+this.dSetMember1.Tables[0].Rows[i][3]+"@"+this.dSetMember1.Tables[0].Rows[i][4]+"|";
sendArray=System.Text.Encoding.BigEndianUnicode.GetBytes(msg.ToCharArray());
Login.Send(sendArray,0,sendArray.Length,0);
}
//向客户端发送结束标识 sendArray=System.Text.Encoding.BigEndianUnicode.GetBytes("Success".ToCharArray());
ogin.Send(sendArray,0,sendArray.Length,0);
Login.Shutdown(SocketShutdown.Both);
sock.Close();
targetTransfer();//重新调用本线程
}客户端代码
while(msg.CompareTo("Success")!=0)
{//获取用户信息
sock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Connect(Server1);
Byte[] msgArray1=new byte[64];
sock.Receive(msgArray1,0,msgArray1.Length,0); msg=System.Text.Encoding.BigEndianUnicode.GetString(msgArray1);
MessageBox.show(msg)
sock.Close();
}可是我在客户端只循环了一次就将服务器端发送的数据全部接收过来了.
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Text;namespace Server
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class DEServerListener
{
protected Socket _socListener = null;
protected ArrayList _clientHandlers = new ArrayList();
protected int _workID = -1;
protected IPAddress [] _aryLocalAddr = null;
protected int _ipPort = 0; public DEServerListener(int ipPort)
{
string _strHostName = "";
_ipPort = ipPort;
try
{
_strHostName = Dns.GetHostName();
IPHostEntry _ipEntry = Dns.GetHostByName( _strHostName );
_aryLocalAddr = _ipEntry.AddressList;
}
catch( Exception e )
{
throw new Exception("Error trying to get local address."+ e.Message );
}
if( _aryLocalAddr == null || _aryLocalAddr.Length < 1 )
{
throw new Exception( "Unable to get local address" );
}
_socListener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
_socListener.Bind( new IPEndPoint( _aryLocalAddr[0], ipPort ) );
//_socListener.Bind( new IPEndPoint( IPAddress.Loopback, _iPort ) ); // For use with localhost 127.0.0.1
_socListener.Listen(100); // Setup a callback to be notified of connection requests
_socListener.BeginAccept( new AsyncCallback(OnConnectRequest ), _socListener );
} ~DEServerListener()
{
GC.Collect();
GC.WaitForPendingFinalizers();
} public void OnConnectRequest( IAsyncResult ar )
{
_workID = -1;
ClientHandler _theClientHandler = null;
Socket _socClient = (Socket)ar.AsyncState;
Socket _client = _socClient.EndAccept(ar); for(int i=0;i<_clientHandlers.Count;i++)
{
if(!((ClientHandler)_clientHandlers[i]).isAvailable)
{
_workID = i;
break;
}
}
if(_workID < 0)
{
_theClientHandler = new ClientHandler(_client);
_clientHandlers.Add(_theClientHandler);
}
else
{
_theClientHandler = (ClientHandler)_clientHandlers[_workID];
}
_theClientHandler.run(_client);
_socClient.BeginAccept( new AsyncCallback( OnConnectRequest ), _socClient);
} internal class ClientHandler
{
protected Socket _socClient = null;
protected int _dataLength = 0;
protected Thread clientTread = null ;
protected bool _isBusy =false;
protected byte[] _bufferData = new byte[255];
// public ClientHandler(Socket client)
// {
// _socClient = client;
// clientTread.Start();
// SetupRecieveCallback(_socClient);
// }
public bool isAvailable
{
get
{
return _isBusy;
}
} public ClientHandler(Socket client)
{
_isBusy = false;
_socClient = client;
clientTread = new Thread (new ThreadStart (ClientSession));
// SetupRecieveCallback(_socClient);
} public void run(Socket client)
{
_isBusy = true;
if(client.Connected)
{
_socClient=client;
SetupRecieveCallback( _socClient );
}
if (clientTread.ThreadState == ThreadState.Unstarted )
{
clientTread.Start();
} if (clientTread.ThreadState == ThreadState.Suspended)
{
clientTread.Resume();
}
if (clientTread.ThreadState == ThreadState.Stopped )
{
clientTread = new Thread (new ThreadStart (ClientSession));
clientTread.Start();
}
}
private void ClientSession()
{
while(true)
{
DateTime now = DateTime.Now;
String strDateLine = "Welcome " + now.ToString("G") + "\n\r"; // Convert to byte array and send.
Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes( strDateLine.ToCharArray() );
if(_socClient.Connected)
{
_socClient.Send( byteDateLine, byteDateLine.Length, 0 );
Console.WriteLine("Connected");
}
clientTread.Suspend();
}
} public void SetupRecieveCallback( Socket sock )
{
try
{
AsyncCallback recieveData = new AsyncCallback( OnRecievedData );
sock.BeginReceive( _bufferData, 0, _bufferData.Length , SocketFlags.None, recieveData, sock );
}
catch( Exception e )
{
Console.WriteLine(" Setup Recieve Callback failed! " + e.Message );
}
} public void OnRecievedData( IAsyncResult ar )
{
byte [] aryRet = GetRecievedData( ar ); // If no data was recieved then the connection is probably dead
if( aryRet.Length < 1 )
{
Console.WriteLine( "Client disconnected" );
_socClient.Close();
_isBusy = false;
return;
} try
{
//process data here
Console.WriteLine(Encoding.ASCII.GetString(aryRet));
//end session if client send "stop"
if(Encoding.ASCII.GetString(aryRet,0,4)=="stop")
{
Byte[] byteClose = Encoding.ASCII.GetBytes("bye");
_socClient.Send( byteClose, byteClose.Length, 0 );
_isBusy = false;
_socClient.Close();
Console.WriteLine( "Client disconnected" );
}
else
{
SetupRecieveCallback( _socClient );
}
}
catch
{
// If the send fails the close the connection
Console.WriteLine( "Send to client {0} failed" );
_socClient.Close();
return;
}
} /// <summary>
/// Data has been recieved so we shall put it in an array and
/// return it.
/// </summary>
/// <param name="ar"></param>
/// <returns>Array of bytes containing the received data</returns>
private byte [] GetRecievedData( IAsyncResult ar )
{
int nBytesRec = 0;
try
{
nBytesRec = _socClient.EndReceive(ar);
}
catch{}
byte [] byReturn = new byte[nBytesRec];
Array.Copy( _bufferData, byReturn, nBytesRec );
// Check for any remaining data and display it
// This will improve performance for large packets
// but adds nothing to readability and is not essential
int nToBeRead = _socClient.Available;
if( nToBeRead > 0 )
{
byte [] byData = new byte[nToBeRead];
_socClient.Receive( byData );
// Append byData to byReturn here
byte [] byReturnMore = new byte[byReturn.Length + byData.Length];
Array.Copy(byReturn,byReturnMore,byReturn.Length);
Array.Copy(byData,0,byReturnMore,byReturn.Length ,byData.Length);
return byReturnMore;
}
return byReturn;
}
}
}
class ServerStartup
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting Server.....");
DEServerListener _DEServerListener = new DEServerListener(399);
Console.WriteLine("Server started, waiting for connections....");
}
catch(Exception e)
{
Console.WriteLine("Server Start Error: {0}",e.Message );
}
Console.ReadLine();
}
}
}