1. package com.yarin.android.Examples_08_04;
2.
3. import java.io.BufferedReader;
4. import java.io.BufferedWriter;
5. import java.io.InputStreamReader;
6. import java.io.OutputStreamWriter;
7. import java.io.PrintWriter;
8. import java.net.ServerSocket;
9. import java.net.Socket;
10.
11. public class Server implements Runnable
12. {
13. public void run()
14. {
15. try
16. {
17. //创建ServerSocket
18. ServerSocket serverSocket = new ServerSocket(54321);
19. while (true)
20. {
21. //接受客户端请求
22. Socket client = serverSocket.accept();
23. System.out.println("accept");
24. try
25. {
26. //接收客户端消息
27. BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
28. String str = in.readLine();
29. System.out.println("read:" + str);
30. //向服务器发送消息
31. PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);
32. out.println("server message");
33. //关闭流
34. out.close();
35. in.close();
36. }
37. catch (Exception e)
38. {
39. System.out.println(e.getMessage());
40. e.printStackTrace();
41. }
42. finally
43. {
44. //关闭
45. client.close();
46. System.out.println("close");
47. }
48. }
49. }
50. catch (Exception e)
51. {
52. System.out.println(e.getMessage());
53. }
54. }
55. //main函数,开启服务器
56. public static void main(String a[])
57. {
58. Thread desktopServerThread = new Thread(new Server());
59. desktopServerThread.start();
60. }
61. }
先开启服务器代码,
java Server即可
然后启动android模拟器。运行结果
这是Android客户端。输入12345,点击发送:
先开启服务器代码,
java Server即可
然后启动android模拟器。运行结果
这是Android客户端。输入12345,点击发送: