我最近开始开发一个 Windows Phone 7.1 应用程序。该应用程序需要服务器从数据库中获取答案。为此,我打算使用套接字和 tcp 连接。
它连接到服务器的效果非常好,但是当我开始尝试流式传输数据时,输出始终是“System.Byte []”。我认为它只是从 byte[] 到字符串的一些错误转换,但它似乎比这更复杂。缓冲区实际上加载了一个 ASCII 符号的 byte[],仅表示“System.Byte[]”。发送的信息是“Bam!” 在长度为 4 的字节 [] 中。我不知道为什么会这样,但从我能够收集到的信息来看,发送的消息似乎只是在传输过程中被修改过。请帮我解决一下这个。
这是我的 Windows Phone 客户端代码
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private IPAddress ServerAddress = new IPAddress(0xff00ff00); //I sensored my IP
private int ServerPort = 13000;
private Socket CurrentSocket;
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
ConnectToServer();
}
catch (Exception exception)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("Error: " + exception.Message));
}
}
private void ConnectToServer()
{
CurrentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Create a new SocketAsyncEventArgs
SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
socketEventArgs.RemoteEndPoint = new IPEndPoint(ServerAddress, ServerPort);
socketEventArgs.Completed += ConnectionCompleted;
socketEventArgs.SetBuffer(new byte[32], 0, 32);
CurrentSocket.ConnectAsync(socketEventArgs);
}
private void ConnectionCompleted(object sender, SocketAsyncEventArgs e)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("You are connected to the server"));
//Create a new SocketAsyncEventArgs
SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
socketEventArgs.RemoteEndPoint = new IPEndPoint(ServerAddress, ServerPort);
socketEventArgs.Completed += MessageReceived;
socketEventArgs.SetBuffer(new byte[32], 0, 32);
CurrentSocket.ReceiveAsync(socketEventArgs);
}
private void MessageReceived(object sender, SocketAsyncEventArgs e)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("You have received a message!"));
string message1 = Convert.ToString(e.Buffer);
string message2 = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
if (message1.Equals(message2))
Dispatcher.BeginInvoke(() => MessageBox.Show(message1));
CurrentSocket.ReceiveAsync(e);
}
}
这是 C# 服务器代码
class ConnectionHandler
{
TcpListener listener;
public ConnectionHandler()
{
listener = new TcpListener(System.Net.IPAddress.Any, 13000);
listener.Start();
while (true)
{
Thread thread = new Thread(Service);
Socket socket = listener.AcceptSocket();
Console.WriteLine("Socket accepted");
thread.Start(socket);
}
}
public void Service(object arg)
{
Socket socket = (Socket)arg;
try
{
Stream stream = new NetworkStream(socket);
Console.WriteLine("Stream created");
string output = "Bam!";
Byte[] bytes = Encoding.UTF8.GetBytes(output);
StreamWriter writer = new StreamWriter(stream);
writer.Write(bytes);
writer.Flush();
writer.Close();
output = Encoding.UTF8.GetString(bytes);
Console.WriteLine("Message sent: " + output);
stream.Close();
}
catch (Exception e)
{
Console.WriteLine("You got an error in ConnectionHandler");
Console.WriteLine(e.Message);
socket.Close();
}
}
}