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(); } } } }

相关文章
相关标签/搜索