我正在创建一个Android应用程序,我需要在其中建立与本地IP地址的连接 我搜索了很多,并找到了我试图在我的代码中实现的相同示例代码
http://android-er.blogspot.in/2011/01/simple-communication-using.html
http://www.pixelstech.net/article/1368328614-Android-socket-programming-example
但问题是我无法连接到没有10.19.21.128
的IP地址
并且没有8221
。
我找不到我失踪的地方。如果有人之前已经做过这个或有想法或任何样本有android app和ip地址之间的通信那么我会感谢他。
注意我只需要将测试消息发送到IP地址。
由于 图莎尔
答案 0 :(得分:1)
客户端
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");
}
}