我想在我的Android智能手机和Win10计算机之间启动TCP连接。我有一个正在运行的C ++服务器,可以很容易地与其他C ++客户端连接。 Xamarin上的C#客户端抛出以下异常:
{System.Net.Sockets.SocketException(0x80004005):在以下位置拒绝连接
System.Net.Sockets.Socket.Connect(System.Net.EndPoint remoteEP)[0x000b6],位于:0处,
AndroidSocketClient.MainActivity.ConnectServer(System.Object发送者,System.EventArgs e)[0x00039]
C ++服务器
#include<io.h>
#include<stdio.h>
#include <string>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc, char* argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(27015);
//Bind
if (bind(s, (struct sockaddr*) & server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr*) & client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
}
puts("Connection accepted");
//Reply to client
const char* message = "Hello Client , I have received your connection. But I have to go now, bye\n";
send(new_socket, message, strlen(message), 0);
getchar();
closesocket(s);
WSACleanup();
return 0;
}
C#-客户端
public void ConnectServer(object sender, System.EventArgs e)
{
byte[] data = new byte[10];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = iphostInfo.AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 27015);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
client.Connect(ipEndpoint);
Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
while (true)
{
string message = "Test";
byte[] sendmsg = Encoding.ASCII.GetBytes(message);
int n = client.Send(sendmsg);
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
}
Console.WriteLine("Transmission end.");
}
经过测试的解决方案:
我已经尝试关闭防火墙并允许Internet连接。
uses-permission android:name="android.permission.INTERNET"