1.首先建立wifi热点服务器 wifi客户端连接
2.开启一个子线程循环监听某个端口,进行数据流输入输出
/* 服务器 接收数据 */
class Receiver extends Thread {
public String receiverContent;
public boolean flag = true;
public ServerSocket serverSocket = null;
public void run() {
try {
// 创建ServerSocket
serverSocket = new ServerSocket(3358);
while (flag) {
// 接受客户端请求
Socket client = serverSocket.accept();
System.out.println("accept");
try {
// 接收客户端消息
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
receiverContent = in.readLine();
System.out.println("read:" + receiverContent);
handler.sendEmptyMessage(0);
// 向客戶端发送消息
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
client.getOutputStream())), true);
out.println("server message");
// 关闭流
out.close();
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
// 关闭
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void close() {
flag = false;
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/* 客户端发送数据 */
class Sender extends Thread {
String serverIp;
String message;
Sender(String serverAddress, String message) {
super();
serverIp = serverAddress;
this.message = message;
}
public void run() {
Socket sock = null;
PrintWriter out;
try {
// 声明sock,其中参数为服务端的IP地址与自定义端口
sock = new Socket(serverIp, 3358);
Log.w("WifiConnection", "I am try to writer" + sock);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 向服务器端发送消息
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream())), true);
out.println(message);
// 接收来自服务器端的消息
BufferedReader br = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
String msg = br.readLine();
Message m = handler.obtainMessage();
m.what = 1;
m.obj = msg;
handler.sendMessage(m);
// 关闭流
out.close();
out.flush();
br.close();
// 关闭Socket
sock.close();
} catch (Exception e) {
LogUtil.e("发送错误:[Sender]run()" + e.getMessage());
}
}
}