我正在編寫允許Android客戶端連接到C#服務器套接字的代碼。客戶端和服務器正常工作,但無法關閉或斷開套接字。無法關閉異步C#服務器套接字連接
服務器由開始的單擊事件:
private void btnStartServer_Click(object sender, EventArgs e)
{
AsynchronousSocketListener Async = new AsynchronousSocketListener();
receiveThread = new Thread(new ThreadStart(Async.StartListening));
receiveThread.Start();
btnStartServer.Enabled = false;
btnStopServer.Enabled = true;
MessageBox.Show("Server Started");
}
然後服務器代碼的大部分:
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// 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 void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 3000);
System.Diagnostics.Debug.WriteLine(ipAddress);
// 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);
Singleton s = Singleton.Instance;
if (s.getIsEnded() == false)
{
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
else
{
listener.Shutdown(SocketShutdown.Both);
listener.Disconnect(true);
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void AcceptCallback(IAsyncResult ar)
{
// 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);
// Signal the main thread to continue.
allDone.Set();
}
public static void ReadCallback(IAsyncResult ar)
{
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)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
if (content.Equals("end<EOF>"))
{
Console.WriteLine("Should end");
Singleton s = Singleton.Instance;
s.setIsEnded(true);
}
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
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());
}
}
}
使用單我可以保持一個獨特的變量來檢查服務器應該運行或不運行。這在上面的方法StartListening()
檢查:
public class Singleton
{
private static Singleton instance;
private Boolean isEnded = false;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
public void setIsEnded(Boolean setter)
{
isEnded = setter;
}
public Boolean getIsEnded()
{
return isEnded;
}
}
最後已試圖通過使用String "end<EOF>"
它發送一個消息到停止服務器。服務器邏輯ReadCallback()
將通知單身人士設置isEnded = true
。這不是一個很好的解決方案,但這是我寫作時能夠半工半讀的唯一方法。斷開插座的邏輯在StartListening()
。理想情況下,它將斷開連接,以便插座可以重新啓動。
當我嘗試斷開連接,然後再次啓動插座會出現此錯誤:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
System.Net.Sockets.SocketException (0x80004005): Only one usage of each socket address (protocol/network address/port) is normally permitted
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at StartServer.AsynchronousSocketListener.StartListening() in c:\Users\Conor\Desktop\StartServer\StartServer\StartServer.cs:line 89
如果我停止服務器,然後試圖發送來自Android客戶端的字符串,在接收到服務器上的消息,然後在服務器控制檯上收到以下消息:
System.Net.Sockets.SocketException (0x80004005): A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
at System.Net.Sockets.Socket.Shutdown(SocketShutdown how)
at StartServer.AsynchronousSocketListener.StartListening()
1.請澄清一下** **斷開意味着_this當我嘗試斷開連接,然後啓動插座again_發生錯誤 - 是它最終''或者是'Singleton.Instance.setIsEnded( true)'在某個button_click處理程序中執行? –
2.另外_如果我停止服務器,然後嘗試從Android客戶端發送一個字符串 - 你如何阻止它(請參閱previos評論)? –
3.並且_信息在服務器上被接收,然後我在服務器console_上收到以下信息 - 您如何知道收到的信息?你在控制檯打印了嗎?什麼時候是「那麼」? –