- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这个程序是关于建立一个服务器和多个客户端之间的连接。握手的过程是客户端生成一个散列值并发送给服务器。服务器端生成一对公钥和私钥并对散列值进行加密,并将加密后的散列值与公钥一起发送回客户端。
我的问题是服务器没有响应我想要的数据,服务器只会响应公钥的签名(加密哈希)。
我的声誉不够高,无法发布结果图片,所以我会直接打出来
另一个问题是我不知道如何修复服务器挂起程序,在 StartListening() 方法的服务器异步类中存在无限循环
有 2 个不同的项目,一个用于服务器,一个用于客户端
服务端代码
异步服务器套接字代码
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
// State object for receiving data from remote device.
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 AsynchronousServerSocket : MonoBehaviour
{
// Thread signal.
public static ManualResetEvent allDone =
new ManualResetEvent (false);
public AsynchronousServerSocket ()
{
}
public Socket listener;
public Server ServerClass;
public ASCIIEncoding myAscii =
new ASCIIEncoding ();
public 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".
IPHostEntry ipHostInfo = Dns.GetHostEntry ("127.0.0.1");
IPAddress ipAddress = ipHostInfo.AddressList [0];
IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 11000);
// Create a TCP/IP 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 (1024);
while (true) {
// Set the event to nonsignaled state.
allDone.Reset ();
// Start an asynchronous socket to listen for connections.
Debug.Log ("Waiting for a connection...");
listener.BeginAccept
(new AsyncCallback (AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne ();
}
//StartCoroutine("StupidUnityHang");
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
public IEnumerator StupidUnityHang ()
{
do {
// Set the event to nonsignaled state.
allDone.Reset ();
// Start an asynchronous socket to listen for connections.
Debug.Log ("Waiting for a connection...");
listener.BeginAccept
(new AsyncCallback (AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne ();
yield return new WaitForSeconds (1);
} while(true);
}
public 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 (StageOne), state);
allDone.WaitOne ();
handler.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback (StageTwo), state);
//allDone.Set();
}
// sending client the signature and the public key
public void StageOne (IAsyncResult ar)
{
String content = String.Empty;
String check = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive (ar);
if (bytesRead > 0) {
state.sb.Append (Encoding.ASCII.GetString (state.buffer, 0, bytesRead));
content = state.sb.ToString ();
byte[] hashByte = myAscii.GetBytes (content);
ServerClass.GeneratePublicPrivateKey ();
byte [] signature = ServerClass.SendEncryptHash (hashByte);
content = myAscii.GetString (signature);
Send (handler, content);
}
}
public void StageTwo (IAsyncResult ar)
{
String content = String.Empty;
String check = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive (ar);
if (bytesRead > 0) {
//state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
//content = state.sb.ToString();
//if(content =="PK")
//{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
RSAParameters publicKey = ServerClass.SendPublicKey ();
rsaCSP.ImportParameters (publicKey);
content = rsaCSP.ToXmlString (false);
Send (handler, content);
//}
}
}
private 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 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);
Debug.Log ("Sent {0} bytes to client." + bytesSent);
handler.Shutdown (SocketShutdown.Both);
handler.Close ();
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
}
服务器进程代码
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System;
public class Server : MonoBehaviour
{
public RSAParameters rsaPrivateKey;
public RSAParameters rsaPublicKey;
public void GeneratePublicPrivateKey ()
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
rsaPrivateKey = rsaCSP.ExportParameters (true);
rsaPublicKey = rsaCSP.ExportParameters (false);
}
public RSAParameters SendPublicKey ()
{
return rsaPublicKey;
}
public byte[] HashAndSign (byte[] encrypted)
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
SHA1Managed hash = new SHA1Managed ();
byte[] hashedData;
rsaCSP.ImportParameters (rsaPrivateKey);
hashedData = hash.ComputeHash (encrypted);
return rsaCSP.SignHash (hashedData, CryptoConfig.MapNameToOID ("SHA1"));
}
public byte[] SendEncryptHash (byte[] tmp)
{
return HashAndSign (tmp);
}
public byte[] SendEncryptAESHash (byte[]hash, byte[]key, byte[]IV)
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
rsaCSP.ImportParameters (rsaPrivateKey);
byte[] decryptedSessionKey = rsaCSP.Decrypt (key, false);
byte[] decryptedSessionIV = rsaCSP.Decrypt (IV, false);
return encrypt_function (hash, decryptedSessionKey, decryptedSessionIV);
}
private static byte[] encrypt_function (byte[] PlainBytes, byte[] Key, byte[] IV)
{
RijndaelManaged Crypto = null;
MemoryStream MemStream = null;
ICryptoTransform Encryptor = null;
CryptoStream Crypto_Stream = null;
try {
Crypto = new RijndaelManaged ();
Crypto.Key = Key;
Crypto.IV = IV;
MemStream = new MemoryStream ();
Encryptor = Crypto.CreateEncryptor (Crypto.Key, Crypto.IV);
Crypto_Stream = new CryptoStream (MemStream, Encryptor, CryptoStreamMode.Write);
Crypto_Stream.Write (PlainBytes, 0, PlainBytes.Length);
} finally {
if (Crypto != null)
Crypto.Clear ();
Crypto_Stream.Close ();
}
return MemStream.ToArray ();
}
}
服务器主程序
using UnityEngine;
using System.Collections;
public class ServerProgram : MonoBehaviour
{
public AsynchronousServerSocket AsynchronousServerClass;
public void Start ()
{
AsynchronousServerClass.StartListening ();
}
}
客户端代码
异步客户端类
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Security.Cryptography;
// State object for receiving data from remote device.
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 AsynchronousClientSocket : MonoBehaviour
{
// The port number for the remote device.
private const int port = 11000;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent (false);
private static ManualResetEvent sendDone = new ManualResetEvent (false);
private static ManualResetEvent receiveDone = new ManualResetEvent (false);
// The response from the remote device.
private String response = String.Empty;
public Client ClientClass;
public ASCIIEncoding myAscii = new ASCIIEncoding ();
public void StartClient ()
{
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry ("127.0.0.1");
IPAddress ipAddress = ipHostInfo.AddressList [0];
IPEndPoint remoteEP = new IPEndPoint (ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect (remoteEP, new AsyncCallback (ConnectCallback), client);
connectDone.WaitOne ();
byte[] hashByte = ClientClass.SendHash ();
string hashString = myAscii.GetString (hashByte);
// Send test data to the remote device.
Send (client, hashString);
sendDone.WaitOne ();
// Receive the response from the remote device.
Receive (client);
receiveDone.WaitOne ();
// Write the response to the console.
Debug.Log ("Signature: " + response);
byte[] signature = myAscii.GetBytes (response);
Send (client, "PK");
sendDone.WaitOne ();
Receive (client);
receiveDone.WaitOne ();
Debug.Log ("PublicKey: " + response);
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
rsaCSP.FromXmlString (response);
RSAParameters publicKey = rsaCSP.ExportParameters (false);
if (ClientClass.VerifyHash (publicKey, hashByte, signature)) {
Debug.Log ("success");
} else {
Debug.Log ("problem");
}
// Release the socket.
client.Shutdown (SocketShutdown.Both);
client.Close ();
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
}
private void ConnectCallback (IAsyncResult ar)
{
try {
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect (ar);
Debug.Log ("Socket connected to {0}" + client.RemoteEndPoint.ToString ());
// Signal that the connection has been made.
connectDone.Set ();
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
private void Receive (Socket client)
{
try {
// Create the state object.
StateObject state = new StateObject ();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (ReceiveCallback), state);
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
private void ReceiveCallback (IAsyncResult ar)
{
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.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));
// Get the rest of the data.
client.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString ();
}
// Signal that all bytes have been received.
receiveDone.Set ();
}
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
private void Send (Socket client, 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.
client.BeginSend (byteData, 0, byteData.Length, 0, new AsyncCallback (SendCallback), client);
}
private void SendCallback (IAsyncResult ar)
{
try {
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend (ar);
Debug.Log ("Sent {0} bytes to server." + bytesSent);
// Signal that all bytes have been sent.
sendDone.Set ();
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
}
客户端处理类方法
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System;
public class Client : MonoBehaviour
{
public string hash;
public byte[] sessionKeyByte;
public byte[] sessionIVByte;
public byte[] sessionKey;
public byte[] sessionIV;
static readonly char[] AvailableCharacters = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '`', '~', '-',
'@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '=', '+', '/',
'{', '}', '[', ']', '|','\\', ':', ';', '"','\'', '<', '>', ',',
'.', '?', '!'
};
internal static string GenerateIdentifier (int length)
{
char[] identifier = new char[length];
byte[] randomData = new byte[length];
RNGCryptoServiceProvider rng =
new RNGCryptoServiceProvider ();
rng.GetBytes (randomData);
for (int idx = 0; idx < identifier.Length; idx++) {
int pos =
randomData [idx] % AvailableCharacters.Length;
identifier [idx] = AvailableCharacters [pos];
}
return new string (identifier);
}
public byte[] SendHash ()
{
hash = GenerateIdentifier (8);
ASCIIEncoding myAscii = new ASCIIEncoding ();
return myAscii.GetBytes (hash);
}
public bool VerifyHash
(RSAParameters rsaParams, byte[] signedData, byte[] signature)
{
RSACryptoServiceProvider rsaCSP =
new RSACryptoServiceProvider ();
SHA1Managed hash = new SHA1Managed ();
byte[] hashedData;
rsaCSP.ImportParameters (rsaParams);
hashedData = hash.ComputeHash (signedData);
return rsaCSP.VerifyHash
(hashedData, CryptoConfig.MapNameToOID ("SHA1"), signature);
}
public void EncryptSessionKey (RSAParameters temp)
{
RijndaelManaged Crypto = new RijndaelManaged ();
RSACryptoServiceProvider rsaCSP =
new RSACryptoServiceProvider ();
rsaCSP.ImportParameters (temp);
sessionKey = Crypto.Key;
sessionIV = Crypto.IV;
sessionKeyByte = rsaCSP.Encrypt (sessionKey, false);
sessionIVByte = rsaCSP.Encrypt (sessionIV, false);
}
public byte[] SendSessionKey ()
{
return sessionKeyByte;
}
public byte[] SendSessionIV ()
{
return sessionIVByte;
}
private static string decrypt_function (
byte[] Cipher_Text, byte[] Key, byte[] IV)
{
RijndaelManaged Crypto = null;
MemoryStream MemStream = null;
ICryptoTransform Decryptor = null;
CryptoStream Crypto_Stream = null;
StreamReader Stream_Read = null;
string Plain_Text;
try {
Crypto = new RijndaelManaged ();
Crypto.Key = Key;
Crypto.IV = IV;
MemStream = new MemoryStream
(Cipher_Text);
Decryptor = Crypto.CreateDecryptor
(Crypto.Key, Crypto.IV);
Crypto_Stream = new CryptoStream
(MemStream, Decryptor, CryptoStreamMode.Read);
Stream_Read = new StreamReader
(Crypto_Stream);
Plain_Text = Stream_Read.ReadToEnd ();
} finally {
if (Crypto != null)
Crypto.Clear ();
MemStream.Flush ();
MemStream.Close ();
}
return Plain_Text;
}
public string DecryptHash (byte[] temp)
{
return decrypt_function (temp, sessionKey, sessionIV);
}
public bool VerifySessionKey (string temp)
{
if (temp == hash) {
return true;
} else {
return false;
}
}
public void ClearHash ()
{
hash = "";
}
}
客户端主程序
using UnityEngine;
using System.Collections.Generic;
public class ClientProgram : MonoBehaviour
{
public string log;
public AsynchronousClientSocket AsynchronousClientClass;
public void OnGUI ()
{
GUILayout.BeginArea (new Rect (Screen.width / 2 - 250, Screen.height / 2 - 250, 500, 500));
GUI.TextArea (new Rect (0, 0, 500, 300), log);
if (GUI.Button (new Rect (200, 310, 100, 30), "Connect")) {
AsynchronousClientClass.StartClient ();
}
GUILayout.EndArea ();
}
}
需要帮助来格式化我的代码,我尝试了很多次来格式化我的代码,但它一直弹出“你的帖子似乎包含代码......甚至都已经在代码选项卡中了。我将所有代码左对齐,然后它运行良好...
我是统一方面的新手,也是网络和安全编程方面的新手,我希望有人能指出我更好的写作方式。
解决了
最佳答案
哎哟……我头疼……试试更简单的东西,比如……
http://ccoder.co.uk/files/sockets.zip
这应该让你继续:)
这是我拥有的一个更大项目(用于统一游戏的 MMO 服务器系统)的代码子集。我真的应该找个时间完成它!!!
关于c# - 需要帮助解决有关异步服务器套接字的一些逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24384090/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!