客戶
class ClientThread implements Runnable {
@Override
public void run() {
try {
socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVERPORT);
socket.connect(socketAddress);
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
final String read1 = input.readLine();
updateConversationHandler.post(new updateUIThread(read1));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
@SuppressLint("SdCardPath")
@Override
public void run() {
text1.setText(text1.getText().toString()+"Server Says: "+ msg + "\n");
}
}
服務器
class ServerThread implements Runnable {
public void run() {
socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
new Thread(new ServerThread()).start();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
final String read1 = input.readLine();
updateConversationHandler.post(new updateUIThread(read1));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
@Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
您的Android設備上安裝connectBot,並嘗試使用它連接到指定的IP和端口。結果可能會提供一個提示。 – alfasin
U的意思是說,如果我檢查模擬器,它將無法工作。目前我正在測試Android模擬器。如果你有相同的示例代碼或Url中實現相同的東西,Plz讓我知道。謝謝 – user3221976
@mani,如果可能,給出完整的代碼。這是一個不完整的朋友。 – user3221976