1. 例子1:客户端发送信息给服务端,服务端将数据显式在控制台上
    2. public class TCPtest1{
    3. //客户端
    4. @Test
    5. public void client(){
    6. Socket socket = null;
    7. OutputStream os = null;
    8. try {
    9. //1.创建Socket对象,指明服务端的ip和端口号
    10. InetAddress inet = InetAddress.getByName("127.0.0.1");
    11. socket = new Socket(inet, 8899);
    12. //2.获取一个输出流,用于输出数据
    13. os = socket.getOutputStream();
    14. os.write("你好我是客户端MM".getBytes());
    15. //3.写出数据的操作
    16. os.close();
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. } finally {
    20. //4.资源的关闭
    21. if (os != null) {
    22. try {
    23. os.close();
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. if (socket != null){
    29. try {
    30. socket.close();
    31. } catch (IOException e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. }
    36. }
    37. //服务端
    38. @Test
    39. public void server(){
    40. ServerSocket ss = null;
    41. Socket socket = null;
    42. InputStream is = null;
    43. ByteArrayOutputStream baos = null;
    44. try {
    45. //1.创建服务器端的SeverSocket,指明自己的端口号
    46. ss = new ServerSocket(8899);
    47. //2.调用accept()表明接收来自于客户端的socket
    48. socket = ss.accept();
    49. //3.读取输入流当中的数据
    50. is = socket.getInputStream();
    51. //不建议这样写,可能有乱码
    52. // byte[] buffer = new byte[1024];
    53. // int len;
    54. // while ((len = is.read(buffer)) != -1){
    55. // String str = new String(buffer, 0 ,len);
    56. // System.out.println(str);
    57. // }
    58. baos = new ByteArrayOutputStream();
    59. byte[] buffer = new byte[5];
    60. int len;
    61. while ((len = is.read(buffer)) != -1){
    62. baos.write(buffer,0,len);
    63. }
    64. System.out.println(baos.toString());
    65. } catch (IOException e) {
    66. e.printStackTrace();
    67. } finally {
    68. //5.关闭资源
    69. if (is != null){
    70. try {
    71. is.close();
    72. } catch (IOException e) {
    73. e.printStackTrace();
    74. }
    75. }
    76. if (baos != null){
    77. try {
    78. baos.close();
    79. } catch (IOException e) {
    80. e.printStackTrace();
    81. }
    82. }
    83. if (socket != null){
    84. try {
    85. socket.close();
    86. } catch (IOException e) {
    87. e.printStackTrace();
    88. }
    89. }
    90. if (ss != null){
    91. try {
    92. ss.close();
    93. } catch (IOException e) {
    94. e.printStackTrace();
    95. }
    96. }
    97. }
    98. }
    99. }