- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在编写允许 Android 客户端连接到 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;
}
}
最后试图通过向服务器发送一 strip 有字符串 "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()
最佳答案
这是一个完整的服务器测试控制台程序。它可以使用 telnet 客户端轻松测试:
telnet localhost 3000
请注意,您将无法看到您键入的内容,但是当您按 Enter 时,所有行都将发送到服务器。但是由于服务器回显了数据(当它收到 <EOF>
字符串时),您将在 telnet 控制台中看到它作为响应。
主要是您的代码。我添加了许多 *Console.WriteLine* 以便您更好地理解事件流、异步 Socket 使用的多线程特性。
注意 while(true)
中的变化循环:当服务器收到 end<EOF>
时它不仅会将 IsEnded 设置为 true,还会设置 ManualResetEvent,以便等待的监听线程解除阻塞并注意到 IsEnded 标志。
另外,为了摆脱第二个 SocketException(在 Socket.Shutdown 中),您不会尝试关闭您的监听套接字。仅关闭您读取和写入的套接字。
另请注意 try-catch(ObjectDisposedException)
在 AcceptCallback: 中使用我的代码,您不太可能偶然发现此异常,但在我编写示例时,我使用它优雅地捕获关闭监听套接字的事件。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Program
{
static void Main(string[] args)
{
var asyncSocketListener = new AsynchronousSocketListener();
var listenerThread = new Thread(asyncSocketListener.StartListening);
listenerThread.Start();
Console.WriteLine("Server Started");
listenerThread.Join();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public class Singleton
{
private static Singleton instance;
private bool isEnded;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
public bool IsEnded
{
get { return isEnded; }
set { isEnded = value; }
}
}
public class AsynchronousSocketListener
{
// State object for reading client data asynchronously
private class StateObject
{
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] Buffer = new byte[BufferSize];
// Client socket.
public Socket WorkSocket;
// Received data string.
public StringBuilder Sb = new StringBuilder();
}
// Thread signal.
private static ManualResetEvent allDone = new ManualResetEvent(false);
public void StartListening()
{
var localEndPoint = new IPEndPoint(IPAddress.Any, 3000);
var 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);
Console.WriteLine("Listening on {0}...", localEndPoint.ToString());
while (true)
{
allDone.Reset();
if (Singleton.Instance.IsEnded)
{
Console.WriteLine("Closing listener socket...");
listener.Close();
break;
}
Console.WriteLine("Waiting for a new connection...");
listener.BeginAccept(AcceptCallback, state: listener);
allDone.WaitOne();
}
Console.WriteLine("Server stopped.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void AcceptCallback(IAsyncResult ar)
{
Socket clientSocket;
try
{
clientSocket = ((Socket)ar.AsyncState).EndAccept(ar);
}
catch (ObjectDisposedException)
{
Console.WriteLine(" Listening socket has been closed.");
allDone.Set();
return;
}
Console.WriteLine(" Connection accepted {0}", clientSocket.RemoteEndPoint.ToString());
var stateObject = new StateObject { WorkSocket = clientSocket };
clientSocket.BeginReceive(stateObject.Buffer, 0, StateObject.BufferSize, 0, ReadCallback, stateObject);
// Signal the main thread to continue.
Console.WriteLine(" Signal the main thread to accept a new connection");
allDone.Set();
}
public static void ReadCallback(IAsyncResult ar)
{
string content;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
var stateObject = (StateObject)ar.AsyncState;
Socket clientSocket = stateObject.WorkSocket;
// Read data from the client socket.
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
stateObject.Sb.Append(Encoding.ASCII.GetString(stateObject.Buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = stateObject.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 stop the server");
Singleton.Instance.IsEnded = true;
allDone.Set();
}
// Echo the data back to the client.
byte[] byteData = Encoding.ASCII.GetBytes(content);
clientSocket.BeginSend(byteData, 0, byteData.Length, 0, WriteCallback, clientSocket);
}
else
{
// Not all data received. Get more.
clientSocket.BeginReceive(stateObject.Buffer, 0, StateObject.BufferSize, 0, ReadCallback, stateObject);
}
}
}
private static void WriteCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
var clientSocket = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = clientSocket.EndSend(ar);
Console.WriteLine(" Sent {0} bytes to client.", bytesSent);
Console.WriteLine(" Disconnecting the client...");
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
Console.WriteLine(" Client disconnected.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
关于c# - 无法关闭异步 C# 服务器套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21403405/
我正在维护一些 Java 代码,我目前正在将它们转换为 C#。 Java 代码是这样做的: sendString(somedata + '\000'); 在 C# 中,我正在尝试做同样的事情: sen
如何确定函数中传递的参数是字符串还是字符(不确定如何正确调用它)文字? 我的函数(不正确): void check(const char* str) { // some code here }
我真的不知道如何准确地提出这个问题,但我希望标题已经说明了这一点。 我正在寻找一种方法(一个框架/库),它提供了执行 String.contains() 函数的能力,该函数告诉我给定的字符串是否与搜索
我正在尝试编写一些读取 Lambda 表达式并输出 beta 缩减版本的东西。 Lambda 的类型如下:\variable -> expression,应用程序的形式为 (表达式) (表达式)。因此
StackOverflow 上的第 1 篇文章,如果我没能把它做好,我深表歉意。我陷入了一个愚蠢的练习,我需要制作一个“刽子手游戏”,我尝试从“.txt”文件中读取单词,然后我得到了我的加密函数,它将
我想在 Groovy 中测试我的 Java 自定义注释,但由于字符问题而未能成功。 Groovyc: Expected 'a' to be an inline constant of type cha
当我尝试在单击按钮期间运行 javascript location.href 时,出现以下错误“字 rune 字中的字符过多”。 最佳答案 这应该使用 OnClientClick相反? 您可能还想停
我想要类似的东西: let a = ["v".utf8[0], 1, 2] 我想到的最接近的是: let a = [0x76, 1, 2] 和 "v".data(using: String.Encod
有没有办法在 MySQL 中指定 Unicode 字 rune 字? 我想用 Ascii 字符替换 Unicode 字符,如下所示: Update MyTbl Set MyFld = Replace(
阅读 PNG 规范后,我有点惊讶。我读过字 rune 字应该用像 0x41 这样的二进制值进行硬编码,而不是在(程序员友好的)'A' 中。问题似乎是在具有不同底层字符集的不同系统上编译期间字 rune
考虑一个具有 UTF-8 执行字符集的 C++11 编译器(并且符合要求 char 类型为有符号 8 位字节的 x86-64 ABI) . 字母 Ä(元音变音)具有 0xC4 的 unicode 代码
为什么即使有 UTF-8 字符串文字,C11 或 C++11 中也没有 UTF-8 字 rune 字?我知道,一般来说,字 rune 字表示单个 ASCII 字符,它与单字节 UTF-8 代码点相同,
我怎样才能用 Jade 做到这一点? how would I do this 我几乎可以做任何事情,除了引入一个 span 中间句子。 最佳答案 h3.blur. how would I do t
这似乎是一个非常简单的问题,但我只是想澄清我的疑问。我正在查看其他开发人员编写的代码。有一些涉及 float 的计算。 示例:Float fNotAvlbl = new Float(-99); 他为什
我想知道第 3 行“if dec:”中的“dec”是什么意思 1 def dec2bin(dec): 2 result='' 3 if dec:
我试图在字符串中查找不包含任何“a”字符的单词。我写了下面的代码,但它不起作用。我怎么能对正则表达式说“不包括”?我不能用“^”符号表示“不是”吗? import re string2 = "asfd
这个问题在这里已经有了答案: Is floating point math broken? (31 个答案) Is floating point arbitrary precision availa
我正在创建一个时尚的文本应用程序,但在某些地方出现错误(“字 rune 字中的字符太多”)。我只写了一个字母,但是当我粘贴它时,它会转换成许多这样的字母:“\uD83C\uDD89”,原始字母是“🆉
我正在尝试检查用户是否在文本框中输入了一个数字值,是否接受了小数位。非常感谢任何帮助。 Private Sub textbox1_AfterUpdate() If IsNumeric(textbox1
我知道一个 Byte 是 8 位,但其他的代表什么?我正在参加一个使用摩托罗拉 68k 架构的汇编类(class),我对目前的词汇感到困惑。 最佳答案 如 operator's manual for
我是一名优秀的程序员,十分优秀!