Socket編程(網絡編程)

網絡通訊的第一要素:IP地址 經過IP地址惟一的定位到互聯網的主機java

經過  IP+port(端口號)  來肯定互聯網的主機上的某個軟件服務器

InetAddress:位於java.net包下網絡

getHostName():獲取IP地址對應的域名socket

getHostAddress():獲取IP地址.net

public class TestInetAddress{server

  public static void main(String[] args){get

    InetAddress inet = InetAddress.getByName("www.baidu.com");域名

    System.out.println(inet);it

    System.out.println(inet.getHostName());io

    System.out.println(inet.getHostAddress());

    // 獲取本機的IP

    InetAddress inet1 = InetAddress.getLocalHost();

  }

}

 

 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

// 客戶端向服務器發送信息,服務器端接受信息並打印到控制檯上,同時發送「已發送信息」給客戶端public class TestTCP2 { // 客戶端 @Test public void client(){ Socket socket = null; OutputStream os = null; InputStream is = null; try { // 創建通訊 socket = new Socket(InetAddress.getByName("127.0.0.1"), 9897); // 向服務端發送信息 os = socket.getOutputStream(); os.write("哈哈,沒我手速快吧".getBytes()); // 顯示的告訴服務端發送完畢 shutdownOutput() socket.shutdownOutput(); // 從服務端接受響應的信息 is = socket.getInputStream(); byte[] b = new byte[1024]; int len; while ((len=is.read(b))!=-1) { String str = new String(b, 0, len); System.out.println(str); } } catch (Exception e) { e.printStackTrace(); }finally { try { is.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } // 服務端 @Test public void server(){ ServerSocket ss =null; Socket s = null; InputStream is =null; OutputStream os = null; try { ss = new ServerSocket(9897); s = ss.accept(); //讀取客戶端發送的數據 is = s.getInputStream(); byte[] b = new byte[1024]; int len; while ((len=is.read(b))!=-1) { String str = new String(b, 0, len); System.out.println(str); } // 響應給客戶端的數據 os = s.getOutputStream(); os.write("太忽然了我考慮一下".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { try { os.close(); is.close(); s.close(); ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }

相關文章
相關標籤/搜索