Re: question about class Socket
- From: "wukun" <wukun@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 21 Feb 2006 03:47:27 -0800
hello,Vadym Stetsyak:
here is the client and server code, the client send a file "c:\test.txt"
which is about 3mb bytes or larger,start the server,the client runs properly
for the first time,but at the second time the client throws an exception. try
it. thanks a lot!
/*client:*/
class TestClient
{
static void Main(string[] args)
{
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHostInfo.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
// Create a TCP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint.
client.Connect(ipEndPoint);
// There is a text file test.txt located in the root directory.
string fileName = @"c:\test.txt";
// Send file fileName to remote device
Console.WriteLine("Sending {0} to the host.", fileName);
client.SendFile(fileName);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
/*server:*/
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1000;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
//byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming
connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
// 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);
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
if (handler.Available > 0)
{
//There might be more data
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
else
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket.",
state.sb.Length);
// Echo the data back to the client.
Send(handler, "Server Received ok!");
}
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
.
- Follow-Ups:
- Re: question about class Socket
- From: Vadym Stetsyak
- Re: question about class Socket
- References:
- Re: question about class Socket
- From: Vadym Stetsyak
- Re: question about class Socket
- Prev by Date: Re: Sending multicast messages from specific IP address
- Next by Date: Re: question about class Socket
- Previous by thread: Re: question about class Socket
- Next by thread: Re: question about class Socket
- Index(es):
Relevant Pages
|
Loading