本文實例為大家分享了Java網絡編程TCP程序設計的具體代碼,供大家參考,具體內容如下
[1] TCP編程的主要步驟
客戶端(client):
1.創建Socket對象,構造方法的形參列表中需要InetAddress類對象和int型值,用來指明對方的IP地址和端口號。
2.通過Socket對象的getOutputStream()方法返回OutputStream抽象類子類的一個對象,用來發送輸出流。
3.通過輸出流的write方法輸出具體的信息。
4.關閉相應的流和Socket對象。
服務端(server):
1.創建ServerSocket類的對象,在構造器中指明端口號。
2.調用ServerSocket類對象的accept()方法,返回一個Socket類的實例。
3.通過Socket實例的getInputStream()方法獲取一個輸入流,用來接收來自客戶端的信息。
4.利用輸入流接收數據,并處理數據。
5.關閉相應的流、Socket對象、ServerSocket對象。
[2] Java源程序 ( 注意:在測試時先開啟服務端方法server(),再開啟客戶端方法client() )
package pack01;import java.io.*;import java.net.*;import org.junit.Test;public class TestNet1 { @Test //***********************客戶端測試方法*********************** public void client() { Socket socket = null; //建立客戶端網絡套接字 OutputStream socket_os = null; //客戶端輸出流 try { //1.獲取本機環路地址 InetAddress inet = InetAddress.getByName("127.0.0.1"); //2.創建Socket對象 socket = new Socket(inet, 10000); //3.獲取輸出流 socket_os = socket.getOutputStream(); //4.客戶端輸出信息 socket_os.write( "客戶端發送信息".getBytes() ); } catch (IOException e) { e.printStackTrace(); } finally { try { //關閉輸出流 socket_os.close(); } catch (IOException e) { e.printStackTrace(); } try { //關閉客戶端套接字 socket.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test //***********************服務端測試方法*********************** public void server() { ServerSocket serSocket = null; Socket socket = null; InputStream socket_is = null; try { serSocket = new ServerSocket(10000); socket = serSocket.accept(); //獲取服務端套接字 socket_is = socket.getInputStream(); //獲取輸入流 byte[] b = new byte[100]; //用于接收信息的字節數組 int len; StringBuffer sb = new StringBuffer(); while( (len = socket_is.read(b)) != -1 ) { sb.append( new String(b,0,len) ); //將字節信息連續保存在buffer數組里 } System.out.println("來自" + socket.getInetAddress().getHostName() + "的信息:"); System.out.println( sb ); } catch (IOException e) { e.printStackTrace(); } finally { try { //關閉輸入流 socket_is.close(); } catch (IOException e) { e.printStackTrace(); } try { //關閉Socket對象 socket.close(); } catch (IOException e) { e.printStackTrace(); } try { //關閉ServerSocket對象 serSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答