SOKCET 요청을 비동기적으로 수락
25544 단어 Sokcet
public
class
XmlSocket
{
//
socket
//
Incoming data from client.
public
static
string
data
=
null
;
//
Thread signal. ManualResetEvent 。
public
static
ManualResetEvent allDone
=
new
ManualResetEvent(
false
);
//
static void Main(string[] args)
//
{
//
StartListening();
//
}
public
static
void
StartListening()
{
//
Data buffer for incoming data.
byte
[] bytes
=
new
Byte[
1024
];
//
Establish the local endpoint for the socket.
//
The DNS name of the computer
//
running the listener is "host.contoso.com".
IPAddress ipAddress;
String ipString
=
ConfigurationManager.AppSettings.Get(
"
SocketIP
"
);
if
(ipString
==
null
||
ipString
==
String.Empty)
{
IPHostEntry ipHostInfo
=
Dns.GetHostEntry(Dns.GetHostName());
ipAddress
=
ipHostInfo.AddressList[
0
];
}
else
{
ipAddress
=
IPAddress.Parse(ipString);
}
int
port;
String portString
=
ConfigurationManager.AppSettings.Get(
"
SocketPort
"
);
if
(portString
==
null
||
portString
==
String.Empty)
{
port
=
11001
;
}
else
{
port
=
int
.Parse(portString);
}
IPEndPoint localEndPoint
=
new
IPEndPoint(ipAddress, port);
//
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.
listener.BeginAccept(
new
AsyncCallback(AcceptCallback), listener);
//
Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch
(Exception e)
{
//
}
}
public
static
void
AcceptCallback(IAsyncResult ar)
{
try
{
//
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);
}
catch
(Exception e)
{
//
}
}
///
<summary>
///
, AsyncCallback 。
///
, BeginReceive , 。
///
, , 。
///
</summary>
///
<param name="ar">
IAsyncResult
</param>
public
static
void
ReadCallback(IAsyncResult ar)
{
try
{
String content
=
String.Empty;
//
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
)
{
//
string
result
=
DoSomeThing(...);
String len
=
Encoding.UTF8.GetBytes(result).Length.ToString().PadLeft(
8
,
'
0
'
);
log.writeLine(len);
Send(len
+
result, handler);
}
}
catch
(Exception e)
{
//
}
}
private
static
void
Send(String data, Socket handler)
{
try
{
//
Convert the string data to byte data using UTF8 encoding.
byte
[] byteData
=
Encoding.UTF8.GetBytes(data);
//
Begin sending the data to the remote device.
handler.BeginSend(byteData,
0
, byteData.Length,
0
,
new
AsyncCallback(SendCallback), handler);
}
catch
(Exception e)
{
//
}
}
///
<summary>
///
///
</summary>
///
<param name="ar"></param>
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);
StateObject state
=
new
StateObject();
state.workSocket
=
handler;
handler.BeginReceive(state.buffer,
0
, StateObject.BufferSize,
0
,
new
AsyncCallback(ReadCallback), state);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch
(Exception e)
{
//
}
}
public
static
void
StopListening()
{
allDone.Close();
log.close();
}
///
<summary>
///
///
</summary>
///
<returns></returns>
private
static
string
DoSomething(
int
i)
{
//
,
}
///
<summary>
///
///
</summary>
///
<param name="strLog">
</param>
public
static
void
WriteLog(
string
strLog)
{
//
}
}