新建Java工程:
1.服务器:
try {
//创建套接字,ip,端口号
ServerSocket socket = new ServerSocket(8801);
System.out.println("socket套接字创建成功");
//客户端接入
while(true){
final Socket con = socket.accept();
System.out.println("客户端接入");
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
InputStream in;
try {
byte[] data = new byte[128];
int len = 0;
//获取输入流,用来读取数据
in = con.getInputStream();
len = in.read(data);
System.out.println("read data:"+new String(data,0,len));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.客户端:
try {
Socket client = new Socket("192.168.1.3",8801);
//获得数据发送通道
OutputStream out = client.getOutputStream();
Scanner sc = new Scanner(System.in);
String message = sc.next();
out.write(message.getBytes());
//获取数据接收通道
InputStream in = client.getInputStream();
int len;
byte[] data = new byte[128];
len = in.read(data);
System.out.println("服务器返回数据:"+new String(data,0,len));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.安卓客戶端
public void sendMessageHandler()
{
try {
Socket client = new Socket("192.168.1.3",8801);
//获得数据发送通道
OutputStream out = client.getOutputStream();
String message = "message from android:";
//发送数据
out.write(message.getBytes());
//获取数据接收通道
InputStream in = client.getInputStream();
int len;
byte[] data = new byte[128];
len = in.read(data);
System.out.println("服务器返回数据:"+new String(data,0,len));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendMessage(View v){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
sendMessageHandler();
}
});
}
安卓Socket客户端开发注意事项:
网络访问不能在主线程(UI线程)中进行,否则程序会崩溃
要创建线程来发起网络访问