当我尝试从 PC 连接到 android 设备时,我发现了一个套接字异常“无法连接,因为目标机器主动拒绝了它”。android设备上的服务器代码:
private void networkOperations()
{
Thread networkThread = new Thread (null, doBackgroundThreadProcessing, "Network");
networkThread.start();
}
private Runnable doBackgroundThreadProcessing = new Runnable()
{
public void run() {
backgroundThreadProcessing();
}
};
private void backgroundThreadProcessing()
{
Socket s = null;
ServerSocket ss = null;
try {
ss = new ServerSocket(8867);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted())
{
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
networkOperations() 正在调用 Main Activity 的 onCreate() 方法。PC(C#)客户端的代码:
class Connection
{
public Connection(String ip, String port)
{
Ip = IPAddress.Parse(ip);
Port = Convert.ToInt32(port);
}
public IPAddress Ip
{
get;
set;
}
public Int32 Port
{
get;
set;
}
public Boolean ConnectionError;
public Socket S;
public void ConnectToServer()
{
IPEndPoint ipe = new IPEndPoint(Ip, Port);
S = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
S.Connect(ipe);
}
catch (SocketException e)
{
}
}
谁能帮我解决这个问题?谢谢。