我试图通过套接字发送几个数据,所以它被转换为字节,然后返回到服务器上的字符串。但我显然只能做一个。
服务器代码:
static void Read(IAsyncResult ar)
{
int fileNameLen = 1;
//int userNameLen = 9;
State newState = (State)ar.AsyncState; //gets state of Socket
Socket handler = newState.Socket_w; //passes Socket to handler
int bytesRead = handler.EndReceive(ar); //terminates Data Receive from Socket.
if (bytesRead > 0)
{
if (flag == 0)
{
fileNameLen = BitConverter.ToInt32(newState.buffer, 0); //gets filename length
fileName = Encoding.UTF8.GetString(newState.buffer, 4, fileNameLen); //gets filename
//userNameLen = BitConverter.ToInt32(newState.buffer, 8);
//getUsername = Encoding.UTF8.GetString(newState.buffer, 8, fileNameLen);
flag++;
}
}
}
客户端代码:
internal static void uploadFile(string host, string username, string getGame, string filename, string filepath)
{
byte[] m_clientData;
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] fileName = Encoding.UTF8.GetBytes(username + "_" + filename);
byte[] fileData = File.ReadAllBytes(filepath);
byte[] fileNameLen = BitConverter.GetBytes(fileName.Length);
//byte[] sendUsername = Encoding.UTF8.GetBytes(username);
//byte[] sendUsernameLen = BitConverter.GetBytes(sendUsername.Length);
//byte[] sendGame = Encoding.UTF8.GetBytes(getGame);
//byte[] sendGameLen = BitConverter.GetBytes(sendGame.Length);
m_clientData = new byte[4 + fileName.Length + fileData.Length];
fileNameLen.CopyTo(m_clientData, 0);
fileName.CopyTo(m_clientData, 4);
fileData.CopyTo(m_clientData, 4 + fileName.Length);
//sendUsernameLen.CopyTo(m_clientData, 0);
//sendUsername.CopyTo(m_clientData, 4);
//sendGameLen.CopyTo(m_clientData, 0);
//sendGame.CopyTo(m_clientData, 4);
clientSock.Connect(host, 8889);
clientSock.Send(m_clientData); //tofix exception
clientSock.Close();
}
我似乎无法在服务器上正确解密它。任何人都可以帮我解决缓冲区大小之类的问题吗?