- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何终止 Websocket 连接?我不是在谈论在任何一端关闭连接,而是在“中间”中断它。我需要测试一些必须在重新连接时发生的应用程序逻辑(通过 SocketIO 处理)。
不,拔掉网线不算数,因为我无法在单元测试中真正实现自动化:-) 此外,我希望只杀死一个特定的连接,而不是所有的连接。
最佳答案
这很痛苦,但这是可能的。你可以找到解释here .代码如下:
using System;
using System.Collections;
using System.Runtime.InteropServices;
/// <summary>
/// This is a class for disconnecting TCP connections.
/// You can get a list of all connections and close by a connection, localIP,
/// remoteIP, localPort and remotePort.
/// </summary>
public class Disconnecter {
//Enumeration of the states
public enum State{
All=0,
Closed=1,
Listen=2,
Syn_Sent=3,
Syn_Rcvd=4,
Established=5,
Fin_Wait1=6,
Fin_Wait2=7,
Close_Wait=8,
Closing=9,
Last_Ack=10,
Time_Wait=11,
Delete_TCB=12
}
//Connection info
private struct MIB_TCPROW{
public int dwState;
public int dwLocalAddr;
public int dwLocalPort;
public int dwRemoteAddr;
public int dwRemotePort;
}
//API to get list of connections
[DllImport("iphlpapi.dll")]
private static extern int GetTcpTable(IntPtr pTcpTable,ref int pdwSize,bool bOrder);
//API to change status of connection
[DllImport("iphlpapi.dll")]
//private static extern int SetTcpEntry(MIB_TCPROW tcprow);
private static extern int SetTcpEntry(IntPtr pTcprow);
//Convert 16-bit value from network to host byte order
[DllImport("wsock32.dll")]
private static extern int ntohs(int netshort);
//Convert 16-bit value back again
[DllImport("wsock32.dll")]
private static extern int htons(int netshort);
//Close all connection to the remote IP
public static void CloseRemoteIP(string IP){
MIB_TCPROW[] rows = getTcpTable();
for(int i=0; i<rows.Length; i++){
if(rows[i].dwRemoteAddr==IPStringToInt(IP)){
rows[i].dwState = (int) State.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}
//Close all connections at current local IP
public static void CloseLocalIP(string IP){
MIB_TCPROW[] rows = getTcpTable();
for(int i=0; i<rows.Length; i++){
if(rows[i].dwLocalAddr==IPStringToInt(IP)){
rows[i].dwState = (int) State.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}
//Closes all connections to the remote port
public static void CloseRemotePort(int port){
MIB_TCPROW[] rows = getTcpTable();
for(int i=0; i<rows.Length; i++){
if(port==ntohs(rows[i].dwRemotePort)){
rows[i].dwState = (int) State.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}
//Closes all connections to the local port
public static void CloseLocalPort(int port){
MIB_TCPROW[] rows = getTcpTable();
for(int i=0; i<rows.Length; i++){
if(port==ntohs(rows[i].dwLocalPort)){
rows[i].dwState = (int) State.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}
//Close a connection by returning the connectionstring
public static void CloseConnection(string connectionstring){
try{
//Split the string to its subparts
string[] parts = connectionstring.Split('-');
if(parts.Length!=4) throw new Exception("Invalid connectionstring - use the one provided by Connections.");
string[] loc = parts[0].Split(':');
string[] rem = parts[1].Split(':');
string[] locaddr = loc[0].Split('.');
string[] remaddr = rem[0].Split('.');
//Fill structure with data
MIB_TCPROW row = new MIB_TCPROW();
row.dwState = 12;
byte[] bLocAddr = new byte[]{byte.Parse(locaddr[0]),byte.Parse(locaddr[1]),byte.Parse(locaddr[2]),byte.Parse(locaddr[3])};
byte[] bRemAddr = new byte[]{byte.Parse(remaddr[0]),byte.Parse(remaddr[1]),byte.Parse(remaddr[2]),byte.Parse(remaddr[3])};
row.dwLocalAddr = BitConverter.ToInt32(bLocAddr,0);
row.dwRemoteAddr = BitConverter.ToInt32(bRemAddr,0);
row.dwLocalPort = htons(int.Parse(loc[1]));
row.dwRemotePort = htons(int.Parse(rem[1]));
//Make copy of the structure into memory and use the pointer to call SetTcpEntry
IntPtr ptr = GetPtrToNewObject(row);
int ret = SetTcpEntry(ptr);
if(ret==-1) throw new Exception("Unsuccessful");
if(ret==65) throw new Exception("User has no sufficient privilege to execute this API successfully");
if(ret==87) throw new Exception("Specified port is not in state to be closed down");
if(ret!=0) throw new Exception("Unknown error ("+ret+")");
}catch(Exception ex){
throw new Exception("CloseConnection failed ("+connectionstring+")! ["+ex.GetType().ToString()+","+ex.Message+"]");
}
}
//Gets all connections
public static string[] Connections(){
return Connections(State.All);
}
//Gets a connection list of connections with a defined state
public static string[] Connections(State state){
MIB_TCPROW[] rows = getTcpTable();
ArrayList arr = new ArrayList();
foreach(MIB_TCPROW row in rows){
if(state == State.All || state == (State)row.dwState){
string localaddress = IPIntToString(row.dwLocalAddr) +":"+ ntohs(row.dwLocalPort);
string remoteaddress = IPIntToString(row.dwRemoteAddr) + ":" + ntohs(row.dwRemotePort);
arr.Add(localaddress + "-" + remoteaddress + "-" + ((State)row.dwState).ToString() + "-" + row.dwState);
}
}
return (string[])arr.ToArray(typeof(System.String));
}
//The function that fills the MIB_TCPROW array with connectioninfos
private static MIB_TCPROW[] getTcpTable(){
IntPtr buffer = IntPtr.Zero; bool allocated=false;
try{
int iBytes=0;
GetTcpTable(IntPtr.Zero, ref iBytes, false); //Getting size of return data
buffer=Marshal.AllocCoTaskMem(iBytes); //allocating the datasize
allocated=true;
GetTcpTable(buffer, ref iBytes, false); //Run it again to fill the memory with the data
int structCount=Marshal.ReadInt32(buffer); // Get the number of structures
IntPtr buffSubPointer = buffer; //Making a pointer that will point into the buffer
buffSubPointer = (IntPtr)((int)buffer + 4); //Move to the first data (ignoring dwNumEntries from the original MIB_TCPTABLE struct)
MIB_TCPROW[] tcpRows = new MIB_TCPROW[structCount]; //Declaring the array
//Get the struct size
MIB_TCPROW tmp = new MIB_TCPROW();
int sizeOfTCPROW = Marshal.SizeOf(tmp);
//Fill the array 1 by 1
for(int i=0; i<structCount; i++){
tcpRows[i] = (MIB_TCPROW)Marshal.PtrToStructure(buffSubPointer, typeof(MIB_TCPROW)); //copy struct data
buffSubPointer = (IntPtr)((int)buffSubPointer + sizeOfTCPROW ); //move to next structdata
}
return tcpRows;
}catch(Exception ex){
throw new Exception("getTcpTable failed! ["+ex.GetType().ToString()+","+ex.Message+"]");
}finally{
if(allocated) Marshal.FreeCoTaskMem(buffer); //Free the allocated memory
}
}
private static IntPtr GetPtrToNewObject(object obj){
IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(obj));
Marshal.StructureToPtr(obj,ptr,false);
return ptr;
}
//Convert an IP string to the INT value
private static int IPStringToInt(string IP){
if(IP.IndexOf(".")<0) throw new Exception("Invalid IP address");
string[] addr = IP.Split('.');
if(addr.Length!=4) throw new Exception("Invalid IP address");
byte[] bytes = new byte[]{byte.Parse(addr[0]),byte.Parse(addr[1]),byte.Parse(addr[2]),byte.Parse(addr[3])};
return BitConverter.ToInt32(bytes,0);
}
//Convert an IP integer to IP string
private static string IPIntToString(int IP){
byte[] addr = System.BitConverter.GetBytes(IP);
return addr[0] +"."+addr[1] +"."+addr[2] +"."+addr[3];
}
}
关于websocket - 如何终止 Websocket 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268419/
如果我终止应用程序,我在尝试保持我的功能运行时卡住了。 是否可以在应用程序未运行时保持核心位置(地理围栏/地理定位)和核心蓝牙运行?如果可能如何解决我的问题?我已经检查了背景模式,并实现了核心定位方法
该程序要求用户输入一个数字,然后从列表中返回详细信息。我该怎么做? do { Scanner in = new Scanner(System.in);
我正在开发一个内部分发的 iOS 应用程序(即,没有应用程序商店),我希望能够以恒定的 10 分钟间隔报告设备的位置。 无论如何,我在我的 plist 中包含了 location 作为字段 UIBac
我的 mongodb 服务器突然收到信号 15(终止)。我不知道为什么 mongodb 崩溃了。以下是日志消息。 Mon Jun 27 07:33:31.701 [signalProcessingTh
我按顺序运行了一堆malloc,并且每次都检查以确保它是成功的。像这样: typedef struct { int *aray; char *string; } mystruct; m
这个问题已经有答案了: How to stop a running pthread thread? (4 个回答) 已关闭 8 年前。 可以使用 pthread_join() 停止线程。但让我们想象一
#include #include #include struct node{ char data; int p; struct node *ptr; }; struct node *st
这个问题已经有答案了: Why should I use a semicolon after every function in javascript? (9 个回答) 已关闭 8 年前。 好吧,我问
我有一个启动多个工作线程的函数。每个工作线程都由一个对象封装,该对象的析构函数将尝试加入线程,即调用if (thrd_.joinable()) thrd_.join();。但是,每个 worker 必
我正在实现一个应用程序,当用户摇动手机时,该应用程序会监听并采取行动。 所以我实现了以下服务: public class ShakeMonitorService extends Service {
我在使用 Xcode 时遇到问题,其中弹出错误“Source Kit Service Terminated”,并且所有语法突出显示和代码完成在 Swift 中都消失了。我怎样才能解决这个问题? 这是一
我想为我的控制台应用程序安全退出,该应用程序将使用单声道在 linux 上运行,但我找不到解决方案来检测信号是否发送到它或用户是否按下了 ctrl+c。 在 Windows 上有内核函数 SetCon
关键: pthread_cancel函数发送终止信号pthread_setcancelstate函数设置终止方式pthread_testcancel函数取消线程(另一功能是:设置取消点) 1 线程取消
下面的程序在不同的选项级别下有不同的行为。当我用 -O3 编译它时,它永远不会终止。当我用 -O0 编译它时,它总是很快就会终止。 #include #include void *f(void *
我有 3 个节点的 K8S 集群,我创建了 3 个副本 pod,应用程序 app1 在所有 pod 上运行,我通过运行 service yaml 文件建立了服务,我可以看到通过运行 kubectl g
我打算使用 nginx 来代理 websocket。在执行 nginx reload/HUP 时,我知道 nginx 等待旧的工作进程停止处理所有请求。然而,在 websocket 连接中,这可能不会
在 Ubuntu 9.10 上使用 PVM 3.4.5-12(使用 apt-get 时的 PVM 包) 添加主机后程序终止。 laptop> pvm pvm> add bowtie-slave add
我编写了一个应用程序来从 iPhone 录制视频。它工作正常,但有一个大问题。当 AVCaptureSession 开始运行并且用户尝试从其库(iPod)播放音频时。此操作将使 AVCaptureSe
我将如何使用NSRunningApplication?我有与启动应用程序相反的东西: [[NSWorkspace sharedWorkspace] launchApplication:appName]
我正在使用 NSTask 执行一系列长时间运行的命令,如下所示: commandToRun = @"command 1;command2"; NSArray *arguments = [NSArray
我是一名优秀的程序员,十分优秀!