我正在通过Socket使用无线路由器从android作为客户端和笔记本电脑作为服务器进行通信。但是如果我想如何安全地进行通信。这是我在eclipse中的android代码
public class TCPClient implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr,12345);
String message = "Hello from Client android emulator";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
这是Netbean中的服务器代码,它正在与android进行通信。我必须做些什么改变?
public class TCPDesktopServer implements Runnable{
public static final String SERVERIP = "10.0.2.15";
public static final int SERVERPORT = 12345;
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: '" + str + "'");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPDesktopServer());
desktopServerThread.start();
}
}
答案 0 :(得分:0)
好像你需要使用javax.crypto.CipherOutputStream / CipherInputStream,或者如果你想要一个更标准化的方法,你可以尝试Apache commons(http://commons.apache.org/),其中有一个基本的SSL实现。
答案 1 :(得分:0)
您可以非常轻松地使用SSLSocket类,它是基本java发行版的一部分。如果您在获取证书时遇到问题,可以使用this教程向您展示如何允许自签名证书和不匹配的主机名。