本文實例為大家分享了Java實現TCP互發消息的具體代碼,供大家參考,具體內容如下
TCP客戶端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
package tcp; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class TcpClient { public static void main(String[] args) { Socket socket = null ; OutputStream os = null ; try { //創建socket對象,指明服務器端的ip和端口號 InetAddress inet = InetAddress.getByName( "127.0.0.1" ); socket = new Socket(inet, 8888 ); //獲取一個輸出流,用于輸出數據 os = socket.getOutputStream(); //寫出數據的操作 os.write( "你好,我是客戶端" .getBytes()); } catch (IOException e){ e.printStackTrace(); } finally { //資源的關閉 if (os!= null ){ try { os.close(); } catch (IOException e){ e.printStackTrace(); } } if (socket!= null ){ try { socket.close(); } catch (IOException e){ e.printStackTrace(); } } } } } |
TCP服務端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package tcp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; class TcpServer{ public static void main(String[] args) { ServerSocket ss= null ; Socket socket= null ; InputStream is= null ; ByteArrayOutputStream baos = null ; try { //創建服務器端的ServerSocket,指明自己的端口 ss = new ServerSocket( 8888 ); //調用accept()表示接收來自于客戶端的socket socket = ss.accept(); //獲取輸入流中的數據 is = socket.getInputStream(); /*讀取輸入流中的數據(ByteArrayOutputStream可以把字節一次性記錄下來, 這樣就可以避免一些字符的字節碼不一致導致發送后解析出現亂碼; ByteArrayOutputStream的功能與StringBuilder的作用有異曲同工之妙。) */ baos = new ByteArrayOutputStream(); byte [] buffer = new byte [ 5 ]; int len; while ((len = is.read(buffer)) != - 1 ) { baos.write(buffer, 0 , len); } System.out.println(baos.toString()); } catch (IOException e){ e.printStackTrace(); } finally { //關閉流 if (baos!= null ){ try { baos.close(); } catch (IOException e){ e.printStackTrace(); } } if (is!= null ){ try { is.close(); } catch (IOException e){ e.printStackTrace(); } } if (socket!= null ){ try { socket.close(); } catch (IOException e){ e.printStackTrace(); } } if (ss!= null ){ try { ss.close(); } catch (IOException e){ e.printStackTrace(); } } } } } |
注意:在Intellij idea中運行時,需先打開兩個端的平行運行設置,操作如下:
最后的運行結果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_45802810/article/details/107623345