是否可以使用套接字编程连接两部手机? 我尝试了以下代码,但它没有用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();//Public function to get ip address to it is //working fine
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(8087);
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
根据套接字编程,两个客户端套接字无法相互连接。类似地,两个服务器套接字无法相互连接。您编写的代码告诉您已编写服务器套接字。你需要一个连接到服务器套接字的客户端套接字。创建客户端套接字你需要ip和服务器套接字端口。请看下面的代码。如果您发现回复对您有用,则不要忘记投票。以下示例位于核心java中。你也可以在andriod中实现两者。
Server
-------
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Client
--------------
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
由于 迪帕克
答案 1 :(得分:1)
是的,这是可能的,但我认为你应该做的第一件事是阅读Java Socket programming,因为你的代码有一些问题让我觉得你还没有完全掌握它。主要问题是:
ServerSocket
从不接受任何关联,因此实际上从未“倾听”。你需要在一部手机上实现一个客户端,而在另一部手机上实现一个服务器,就像@Deepak所示。
此外,您可能需要查看this article中的AsyncTask
,以便从非UI线程(而不是处理程序)更新视图。
最后,请确保您的应用包含android.permission.INTERNET
中的AndroidManifest.xml
权限。