黑马程序员 Java基础 网络编程

来源:互联网 发布:深圳燕麦科技知乎 编辑:程序博客网 时间:2024/04/29 06:54

对于网络,java提供了丰富的API,可以很方便的访问互联网上的HTTP服务,可以直接取得网络上的资源,因为java最初就是作为一门网络编程语言出现的。不过要学习java编程,需要先了解一些概念。

一、网络基本概念

1、IP地址

IP地址是用来标识计算机等网络设备的网络地址,由4个8位的二进制组成,中间有小数点分隔。

2、主机名

网络地址的助记名,按域名分级管理。

3、端口号

网络通信时,同一机器上的不同进程标识,其中0-1023是公认端口号。1024-65535是没有公共定义的端口号。

4、服务类型

网络存在各种服务,如HTTP,Telnet、FTP、SMtp。服务类型是应用层上的概念。

5、TCP/IP协议

它实际是一组协议,包括了上百个各种功能的协议,TCP/IP是一个可靠的、需要连接的,但传输效率较慢,TCP里存在一个UDP协议,它不需要连接,但传输效率高。

二、java网路编程API


1、InetAddress类

它是IP地址的封装类,它没有构造方法,但它提供了一些静态方法来返回它的对象。

public class InetTest {public static void main(String[] args) throws Exception{//获取本机IP地址          InetAddress ia = InetAddress.getLocalHost();          System.out.println(ia.toString());            //通过新浪主机名获取其IP地址          InetAddress i = InetAddress.getByName();         System.out.println("name:" + i.getHostName());          System.out.println("address:" + i.getHostAddress());}}
2、DatagramSocket和DatagramPacket

它们是利用UDP协议传输数据包的。

public class Udp {public static void main(String[] args) throws Exception{DatagramSocket ds=new DatagramSocket();DatagramSocket dk=new DatagramSocket(10005);new Thread(new TalkSend(ds)).start();new Thread(new TalkRece(dk)).start();}}class TalkSend implements Runnable{private DatagramSocket ds=null;TalkSend(DatagramSocket ds){this.ds=ds;}public void run(){try {BufferedReader bfd = new BufferedReader(new InputStreamReader(System.in));String str;while ((str = bfd.readLine()) != null) {byte[] by=str.getBytes();DatagramPacket dp = new DatagramPacket(by, by.length,InetAddress.getLocalHost(), 10005);ds.send(dp);}} catch (Exception e) {// TODO: handle exception}ds.close();}}class TalkRece implements Runnable{private DatagramSocket ds=null;TalkRece(DatagramSocket ds){this.ds=ds;}public void run(){try {while(true){byte[] bt = new byte[1024];DatagramPacket dp = new DatagramPacket(bt, bt.length);ds.receive(dp);System.out.println(dp.getAddress());System.out.println(new String(dp.getData(), 0, dp.getData().length));}} catch (Exception e) {// TODO: handle exception}}
这是Datagram的典型应用,用UDP协议来建立的一个对话小程序,端口的问题需要注意。

3、ServerSocket和Socket

Socket是基于TCP/IP进行通讯的,它是连接的,可靠的,通过Socket,可以很容易实现计算机之间的通讯。

Socket是客户端,它里面封装了输入输出流,可是实现计算机之间的数据交流,而ServerSocket它可以接受Socket,并利用Socket里面的输入输出流来进行计算机之间的通讯。下面就是一个如何构建客户端和服务端的例子。


//客户端  class TransClient  {      public static void main(String[] args) throws Exception      {          //创建Socket服务          Socket s = new Socket("192.168.1.103",10009);          //定义读取键盘数据的流对象          BufferedReader bufr =              new BufferedReader(new InputStreamReader(System.in));          //定义目的,将数据写入到socket输出流,发送服务端          //BufferedWriter bufOut =           //  new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));          PrintWriter out = new PrintWriter(s.getOutputStream(),true);          //定义一个socket读取流,读取服务端返回的信息,数据          BufferedReader bufIn =               new BufferedReader(new InputStreamReader(s.getInputStream()));            String line = null;          while((line=bufr.readLine())!=null)          {              if("over".equals(line))                  break;              out.println(line);              //bufOut.write(line);              //bufOut.newLine();              //bufOut.flush();                String str = bufIn.readLine();              System.out.println("Server:" + str);          }          bufr.close();          s.close();      }  }  import java.io.*;  import java.net.*;    //服务端  class TransSever  {      public static void main(String[] args) throws Exception      {          ServerSocket ss = new ServerSocket(10009);          Socket s = ss.accept();                    String ip = s.getInetAddress().getHostAddress();          System.out.println(ip+"....connected");            BufferedReader bufIn =              new BufferedReader(new InputStreamReader(s.getInputStream()));          //BufferedWriter bufOut =          //  new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));          PrintWriter out = new PrintWriter(s.getOutputStream(),true);          String line = null;          while((line=bufIn.readLine())!=null)          {              System.out.println(line);              out.println(line.toUpperCase());              //bufOut.write(line.toUpperCase());              //bufOut.newLine();              //bufOut.flush();          }          s.close();          ss.close();      }  }  


0 0
原创粉丝点击