本文實(shí)例為大家分享了Java網(wǎng)絡(luò)編程TCP程序設(shè)計(jì)的具體代碼,供大家參考,具體內(nèi)容如下
[1] TCP編程的主要步驟
客戶端(client):
1.創(chuàng)建Socket對(duì)象,構(gòu)造方法的形參列表中需要InetAddress類對(duì)象和int型值,用來指明對(duì)方的IP地址和端口號(hào)。
2.通過Socket對(duì)象的getOutputStream()方法返回OutputStream抽象類子類的一個(gè)對(duì)象,用來發(fā)送輸出流。
3.通過輸出流的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.通過Socket實(shí)例的getInputStream()方法獲取一個(gè)輸入流,用來接收來自客戶端的信息。
4.利用輸入流接收數(shù)據(jù),并處理數(shù)據(jù)。
5.關(guān)閉相應(yīng)的流、Socket對(duì)象、ServerSocket對(duì)象。
[2] Java源程序 ( 注意:在測(cè)試時(shí)先開啟服務(wù)端方法server(),再開啟客戶端方法client() )
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("來自" + 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ǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選