[关闭]
@Yano 2016-01-03T16:41:18.000000Z 字数 1537 阅读 3488

Android TCP 简单实现

Android


说明

测试程序分为两个部分:Android 客户端、Java 服务端。

Android 客户端

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. new Thread(new Client()).start();
  7. }
  8. Socket socket = null;
  9. BufferedWriter writer = null;
  10. BufferedReader reader = null;
  11. public class Client implements Runnable {
  12. public void run() {
  13. try {
  14. socket = new Socket("172.24.187.1", 12345);
  15. writer = new BufferedWriter(new OutputStreamWriter(
  16. socket.getOutputStream()));
  17. reader = new BufferedReader(new InputStreamReader(
  18. socket.getInputStream()));
  19. } catch (UnknownHostException e) {
  20. e.printStackTrace();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. try {
  25. // 接收信息
  26. // String line;
  27. // while ((line = reader.readLine()) != null) {
  28. // System.out.println(line);
  29. // }
  30. // 发送信息
  31. // 发送字符串要加\n
  32. if (writer != null) {
  33. writer.write("abcd\n");
  34. writer.flush();
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. }

Java 客户端

  1. public class ServerTest {
  2. public static void main(String[] args) {
  3. Thread thread = new Thread(new Runnable() {
  4. public void run() {
  5. try {
  6. ServerSocket serverSocket = new ServerSocket(12345);
  7. while (true) {
  8. // block
  9. Socket socket = serverSocket.accept();
  10. System.out.println("建立连接");
  11. // 接收消息
  12. BufferedReader br = new BufferedReader(
  13. new InputStreamReader(socket.getInputStream(),
  14. "UTF-8"));
  15. String line = null;
  16. while ((line = br.readLine()) != null) {
  17. System.out.println(line);
  18. }
  19. br.close();
  20. // 发送消息
  21. // socket.getOutputStream().write((out+"\n").getBytes("UTF-8"));
  22. }
  23. } catch (HeadlessException e) {
  24. e.printStackTrace();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. });
  30. thread.start();
  31. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注