Java学习网络编程
大纲
- 网络相关概念
- IP地址
- 网络协议
- InetAdress
- Socket
具体案例
1. 网络相关概念
网络
网络通信
2. IP地址
域名
3.网络协议
4. InetAdress
获得本机的名字和IP
public static void main(String[] args) throws UnknownHostException {InetAddress inetAddress = InetAddress.getLocalHost();System.out.println(inetAddress);}
获取指定主机名字或域名的信息
public static void main(String[] args) throws UnknownHostException {InetAddress host1 = InetAddress.getByName(" ");InetAddress host2 = InetAddress.getByName("www.baidu.com");System.out.println(host1);System.out.println(host2);}
gethostname 是获取主机名字。或者域名
getHostAddress 是获取IP地址
public static void main(String[] args) throws UnknownHostException {InetAddress host1 = InetAddress.getByName("挽天");InetAddress host2 = InetAddress.getByName("www.baidu.com");String f2 = host2.getHostAddress();String f1 = host1.getHostAddress();String name = host2.getHostName();System.out.println(f1);System.out.println(f2);System.out.println(name);}
5. Socket
TCP编程
结束标记
通用:调用socket对象的shutdownOutput()方法
其它:在写入时可以用writeNewLine()来进行结束标记,但这要求读取必须使用readline()方法
注意:写完过后记得使用flush方法刷新
服务端
public class socketServer {public static void main(String[] args) throws IOException {//服务端//在本机的9999端口监听,等待连接//前提该端口没有被占用//这个serverSocket,可以通过accept()来返回多个socket(高并发,多个客户端来连接服务器端)ServerSocket serverSocket = new ServerSocket(9999);//当没有客户端连接该端口时。程序会堵塞等待连接// 如果在客户端连接,就会返回Socket对象,程序继续执行Socket socket = serverSocket.accept();//创建一个和这个socket相关的输入流InputStream inputStream = socket.getInputStream();byte [] buf = new byte[1024];int length = 0;while ((length = inputStream.read(buf)) != -1){//根据读取到的实际长度读取字符串System.out.println(new String(buf,0,length));}//创建一个socket相关的输出流OutputStream outputStream = socket.getOutputStream();outputStream.write("hello,client".getBytes());outputStream.flush();//设置一个结束标记代表传入结束socket.shutdownOutput();//关闭流inputStream.close();outputStream.close();//关闭这个对象socket.close();serverSocket.close();}
}
客户端
public class socketClient {public static void main(String[] args) throws IOException {//客户端//连接服务器,里面写一个主机地址和端口,这里写的是本机//如果联机成功,返回一个socket对象Socket socket = new Socket(InetAddress.getLocalHost(),9999);//得到一个和socket对象关联的输出流OutputStream outputStream = socket.getOutputStream();//通过输出流,写入数据到数据通道outputStream.write("hello,server".getBytes());outputStream.flush();//设置一个结束标记socket.shutdownOutput();//获取和与socket相关联的输入流InputStream inputStream = socket.getInputStream();byte[] bytes = new byte[1024];int length;//创建循环读取数据while ((length = inputStream.read(bytes)) != -1){System.out.println(new String(bytes,0,length));}//关闭流对象,和socket,避免资源浪费inputStream.close();outputStream.close();socket.close();}
}