本文實(shí)例為大家分享了java網(wǎng)絡(luò)編程tcp程序設(shè)計(jì)的具體代碼,供大家參考,具體內(nèi)容如下
[1] tcp編程的主要步驟
客戶端(client):
1.創(chuàng)建socket對(duì)象,構(gòu)造方法的形參列表中需要inetaddress類對(duì)象和int型值,用來(lái)指明對(duì)方的ip地址和端口號(hào)。
2.通過(guò)socket對(duì)象的getoutputstream()方法返回outputstream抽象類子類的一個(gè)對(duì)象,用來(lái)發(fā)送輸出流。
3.通過(guò)輸出流的write方法輸出具體的信息。
4.關(guān)閉相應(yīng)的流和socket對(duì)象。
服務(wù)端(server):
1.創(chuàng)建serversocket類的對(duì)象,在構(gòu)造器中指明端口號(hào)。
2.調(diào)用serversocket類對(duì)象的accept()方法,返回一個(gè)socket類的實(shí)例。
3.通過(guò)socket實(shí)例的getinputstream()方法獲取一個(gè)輸入流,用來(lái)接收來(lái)自客戶端的信息。
4.利用輸入流接收數(shù)據(jù),并處理數(shù)據(jù)。
5.關(guān)閉相應(yīng)的流、socket對(duì)象、serversocket對(duì)象。
[2] java源程序 ( 注意:在測(cè)試時(shí)先開(kāi)啟服務(wù)端方法server(),再開(kāi)啟客戶端方法client() )
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package pack01; import java.io.*; import java.net.*; import org.junit.test; public class testnet1 { @test //***********************客戶端測(cè)試方法*********************** public void client() { socket socket = null ; //建立客戶端網(wǎng)絡(luò)套接字 outputstream socket_os = null ; //客戶端輸出流 try { //1.獲取本機(jī)環(huán)路地址 inetaddress inet = inetaddress.getbyname( "127.0.0.1" ); //2.創(chuàng)建socket對(duì)象 socket = new socket(inet, 10000 ); //3.獲取輸出流 socket_os = socket.getoutputstream(); //4.客戶端輸出信息 socket_os.write( "客戶端發(fā)送信息" .getbytes() ); } catch (ioexception e) { e.printstacktrace(); } finally { try { //關(guān)閉輸出流 socket_os.close(); } catch (ioexception e) { e.printstacktrace(); } try { //關(guān)閉客戶端套接字 socket.close(); } catch (ioexception e) { e.printstacktrace(); } } } @test //***********************服務(wù)端測(cè)試方法*********************** public void server() { serversocket sersocket = null ; socket socket = null ; inputstream socket_is = null ; try { sersocket = new serversocket( 10000 ); socket = sersocket.accept(); //獲取服務(wù)端套接字 socket_is = socket.getinputstream(); //獲取輸入流 byte [] b = new byte [ 100 ]; //用于接收信息的字節(jié)數(shù)組 int len; stringbuffer sb = new stringbuffer(); while ( (len = socket_is.read(b)) != - 1 ) { sb.append( new string(b, 0 ,len) ); //將字節(jié)信息連續(xù)保存在buffer數(shù)組里 } system.out.println( "來(lái)自" + socket.getinetaddress().gethostname() + "的信息:" ); system.out.println( sb ); } catch (ioexception e) { e.printstacktrace(); } finally { try { //關(guān)閉輸入流 socket_is.close(); } catch (ioexception e) { e.printstacktrace(); } try { //關(guān)閉socket對(duì)象 socket.close(); } catch (ioexception e) { e.printstacktrace(); } try { //關(guān)閉serversocket對(duì)象 sersocket.close(); } catch (ioexception e) { e.printstacktrace(); } } } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/EarthPioneer/p/9450280.html