@Yano
2016-01-03T16:41:18.000000Z
字数 1537
阅读 3488
Android
测试程序分为两个部分:Android 客户端、Java 服务端。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Client()).start();
}
Socket socket = null;
BufferedWriter writer = null;
BufferedReader reader = null;
public class Client implements Runnable {
public void run() {
try {
socket = new Socket("172.24.187.1", 12345);
writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// 接收信息
// String line;
// while ((line = reader.readLine()) != null) {
// System.out.println(line);
// }
// 发送信息
// 发送字符串要加\n
if (writer != null) {
writer.write("abcd\n");
writer.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class ServerTest {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(12345);
while (true) {
// block
Socket socket = serverSocket.accept();
System.out.println("建立连接");
// 接收消息
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream(),
"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
// 发送消息
// socket.getOutputStream().write((out+"\n").getBytes("UTF-8"));
}
} catch (HeadlessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}