本文實(shí)例為大家分享了Java實(shí)現(xiàn)TCP互發(fā)消息的具體代碼,供大家參考,具體內(nèi)容如下
TCP客戶(hù)端:
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 { //創(chuàng)建socket對(duì)象,指明服務(wù)器端的ip和端口號(hào) InetAddress inet = InetAddress.getByName( "127.0.0.1" ); socket = new Socket(inet, 8888 ); //獲取一個(gè)輸出流,用于輸出數(shù)據(jù) os = socket.getOutputStream(); //寫(xiě)出數(shù)據(jù)的操作 os.write( "你好,我是客戶(hù)端" .getBytes()); } catch (IOException e){ e.printStackTrace(); } finally { //資源的關(guān)閉 if (os!= null ){ try { os.close(); } catch (IOException e){ e.printStackTrace(); } } if (socket!= null ){ try { socket.close(); } catch (IOException e){ e.printStackTrace(); } } } } } |
TCP服務(wù)端:
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 { //創(chuàng)建服務(wù)器端的ServerSocket,指明自己的端口 ss = new ServerSocket( 8888 ); //調(diào)用accept()表示接收來(lái)自于客戶(hù)端的socket socket = ss.accept(); //獲取輸入流中的數(shù)據(jù) is = socket.getInputStream(); /*讀取輸入流中的數(shù)據(jù)(ByteArrayOutputStream可以把字節(jié)一次性記錄下來(lái), 這樣就可以避免一些字符的字節(jié)碼不一致導(dǎo)致發(fā)送后解析出現(xiàn)亂碼; 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 { //關(guān)閉流 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中運(yùn)行時(shí),需先打開(kāi)兩個(gè)端的平行運(yùn)行設(shè)置,操作如下:
最后的運(yùn)行結(jié)果如下:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_45802810/article/details/107623345