我尝试使用套接字创建客户端-服务器应用程序。我已经用 AVD 成功地做到了这一点,并在我的电脑上运行服务器和客户端。但是当我尝试让它在我设备上的同一个 Wifi 网络中工作时,应用程序就会崩溃。
是的,我正在使用单独的线程进行连接,并且已经将 Internet 的使用添加到清单中。
这是一些代码...
客户端线程:
package com.mainlauncher;
import java.io.*;
import java.net.*;
public class ConnectionThread extends Thread {
private static final int SERVERPORT = 7777;
private static final String SERVERADDRESS = "My-PC";
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
@Override
public void run() {
super.run();
open();
close();
}
void open(){
try{
socket = new Socket(SERVERADDRESS,SERVERPORT);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch(IOException e){}
}
void close(){
try {
if(in!=null)
in.close();
if(out!=null)
out.close();
if(socket!=null)
socket.close();
}
catch (IOException e) {}
socket=null;
}
}
服务器端主要:
import java.io.IOException;
import java.net.*;
public class Main {
public static void main(String[] args) {
int port = 7777;
new Main().handleClients(port);
}
private void handleClients(int port) {
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(port);
System.out.println("Server is ready...");
for(int i=1; ; i++){
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.run();
}
}
catch (Exception e){
System.err.println(e.getMessage());
}
finally{
if(serverSocket != null){
try{ serverSocket.close(); }
catch(IOException x){}
}
}
}
}
和服务器线程:
import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
private int serverIndex;
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
public ServerThread (int serverIndex, Socket socket){
this.serverIndex = serverIndex;
this.socket = socket;
}
@Override
public void run() {
super.run();
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(serverIndex + " Disconnected");
}
finally{
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {}
}
}
}
我试着在这里寻找答案\谷歌等......没有任何帮助。没有防火墙或任何东西可以阻止我电脑上的传入连接。
有什么想法吗?
谢谢, 利奥兹