跨平台通信研究之一安卓系统与windows服务器socket通信
服务器端
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Server a = new Server();
a.dopost();
}
public void dopost() {
try {
ServerSocket s = new ServerSocket(12345);
while (true) {
Socket c = s.accept();
System.out.println(c.getInetAddress().getHostAddress());
InputStream in = c.getInputStream();
byte[] b = new byte[1024];
int length = in.read(b);
String ss = new String(b, 0, length);
System.out.println(ss);
System.out.println("33333333333333");
OutputStream oi = c.getOutputStream();
System.out.println("44444444444");
oi.write("服务器推送".getBytes("UTF-8"));
in.close();
oi.close();
c.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
安卓客户端
package com.example.sss;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Socket sk = new Socket("192.168.1.101", 12345);
OutputStream oi = sk.getOutputStream();
oi.write("客户端推送".getBytes());
InputStream is = sk.getInputStream();
byte[] b = new byte[1024];
int leng = is.read(b);
String ss = new String(b, 0, leng, "UTF-8");
System.out.println(ss);
oi.close();
is.close();
sk.close();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
});
t.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}