java基础之 网络编程

来源:互联网 发布:手机淘宝能评论吗 编辑:程序博客网 时间:2024/05/16 08:10

一、网络编程概述

通信协议

通讯的规则

常见协议:TCP、  UDP

 ip地址  

网络中设备的标识

不易记忆,可用主机名

本地回环地址:127.0.0.1  主机名:localhost

端口号

用于标识进程的逻辑地址

有效端口: 0~65535,其中0~1024系统使用或保留端口。

二、IP地址

类 InetAddress

方法摘要 booleanequals(Object obj)
          将此对象与指定对象比较。 byte[]getAddress()
          返回此 InetAddress 对象的原始 IP 地址。static InetAddress[]getAllByName(String host)
          在给定主机名的情况下,根据系统上配置的名称服务返回其 IP 地址所组成的数组。static InetAddressgetByAddress(byte[] addr)
          在给定原始 IP 地址的情况下,返回 InetAddress 对象。static InetAddressgetByAddress(String host, byte[] addr)
          根据提供的主机名和 IP 地址创建 InetAddress。static InetAddressgetByName(String host)
          在给定主机名的情况下确定主机的 IP 地址。 StringgetCanonicalHostName()
          获取此 IP 地址的完全限定域名。 StringgetHostAddress()
          返回 IP 地址字符串(以文本表现形式)。 StringgetHostName()
          获取此 IP 地址的主机名。static InetAddressgetLocalHost()
          返回本地主机。 inthashCode()
          返回此 IP 地址的哈希码。 booleanisAnyLocalAddress()
          检查 InetAddress 是否是通配符地址的实用例行程序。 booleanisLinkLocalAddress()
          检查 InetAddress 是否是链接本地地址的实用例行程序。 booleanisLoopbackAddress()
          检查 InetAddress 是否是回送地址的实用例行程序。 booleanisMCGlobal()
          检查多播地址是否具有全球范围的实用例行程序。 booleanisMCLinkLocal()
          检查多播地址是否具有链接范围的实用例行程序。 booleanisMCNodeLocal()
          检查多播地址是否具有节点范围的实用例行程序。 booleanisMCOrgLocal()
          检查多播地址是否具有组织范围的实用例行程序。 booleanisMCSiteLocal()
          检查多播地址是否具有站点范围的实用例行程序。 booleanisMulticastAddress()
          检查 InetAddress 是否是 IP 多播地址的实用例行程序。 booleanisReachable(int timeout)
          测试是否可以达到该地址。 booleanisReachable(NetworkInterface netif, int ttl, int timeout)
          测试是否可以达到该地址。 booleanisSiteLocalAddress()
          检查 InetAddress 是否是站点本地地址的实用例行程序。 StringtoString()
          将此 IP 地址转换为 String。

三、TCP和UDP通信协议

UDP

不需要建立连接。

数据源和目的封装到数据包中,大小限制在64k内。

不可靠,会丢包。

速度快。

TCP

通过三次握手完成连接,是可靠协议。

建立连接,形成传输数据的通道。

在连接中进行大数据量传输。

效率稍低。

 

四、UDP--聊天

 

import java.io.*;import java.net.*;class Send implements Runnable{ private DatagramSocket ds; public Send(DatagramSocket ds) {  this.ds = ds; } public void run() {  try  {   BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));   String line = null;   while((line=bufr.readLine())!=null)   {    if("886".equals(line))     break;    byte[] buf = line.getBytes();    DatagramPacket dp =      new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.56.255"),10000);    ds.send(dp);   }  }  catch (Exception e)  {   throw new RuntimeException("发送端失败");   }

 }}class Rece implements Runnable{ private DatagramSocket ds; public Rece(DatagramSocket ds) {  this.ds = ds; } public void run() {  try  {   while(true)   {    byte[] buf = new byte[1024];    DatagramPacket dp = new DatagramPacket(buf,buf.length);    ds.receive(dp);    String ip = dp.getAddress().getHostAddress();    String data = new String(dp.getData(),0,dp.getLength());    System.out.println(ip+":"+data);   }  }  catch (Exception e)  {   throw new RuntimeException("接收端失败");   } }}

class ChatDemo { public static void main(String[] args) throws Exception {  DatagramSocket sendSocket = new DatagramSocket();  DatagramSocket receSocket = new DatagramSocket(10000);  new Thread(new Send(sendSocket)).start();  new Thread(new Rece(receSocket)).start(); }}

五、TCP--上传图片

  

import java.io.*;  import java.net.*;    public class PicClient {        public static void main(String[] argsthrows UnknownHostExceptionIOException {          Socket s = new Socket("192.168.56.1",10086);          FileInputStream fis = new FileInputStream("C:\\1.bmp");          OutputStream out = s.getOutputStream();          byte[] buf = new byte[1024];          int len = 0;          while((len = fis.read(buf)) != -1){              out.write(buf);              out.flush();          }          //告诉服务端数据已写完。           s.shutdownOutput();          fis.close();          out.close();          s.close();      }  }  class PicServer{      public static void main(String[] argsthrows IOException{          ServerSocket ss = new ServerSocket(10086);          Socket s = ss.accept();          InputStream in = s.getInputStream();          FileOutputStream fos = new FileOutputStream("d:\\b.bmp");          byte[] buf = new byte[1024];          int len = 0;          while((len = in.read(buf)) !=-1){              fos.write(buf,0,len);              fos.flush();          }          fos.close();          s.close();          ss.close();                }  }  

 

服务端

单线程的服务端有个局限性。当A客户端连接上以后。被服务端获取到。服务端执行具体流程。

这时B客户端连接,只有等待。

因为服务端还没有处理完A客户端的请求,不能循环回来执行下次accept方法。所以暂时获取不到B客户端对象。

 

为了可以让多个客户端同时并发访问服务端。

服务端最好就是将每个客户端封装到一个单独的线程中,这样就可以同时处理多个客户端请求。

 

如何定义线程呢?

只要明确了每一个客户端要在服务端执行的代码即可,将该代码封装在run方法中。

代码如下:

 

import java.io.*;  import java.net.*;  public class PicClient {        public static void main(String[] argsthrows UnknownHostException,              IOException {          Socket s = new Socket("192.168.56.1"10086);          FileInputStream fis = new FileInputStream("c:\\1.bmp");          OutputStream out = s.getOutputStream();          byte[] buf = new byte[1024];          int len = 0;          while ((len = fis.read(buf)) != -1) {              out.write(buf);              out.flush();          }          // 告诉服务端数据已写完。           s.shutdownOutput();          fis.close();          out.close();          s.close();      }  }  class PicServer {      public static void main(String[] argsthrows IOException {          ServerSocket ss = new ServerSocket(10086);          Socket s = null;          while (true){              s = ss.accept();              new Thread(new PicThread(s)).start();          }                }  }  class PicThread implements Runnable {      Socket s = null;      PicThread(Socket s) {          this.s = s;      }      public void run() {          try {              InputStream in = s.getInputStream();              FileOutputStream fos;              fos = new FileOutputStream("d:\\b"+Thread.currentThread().getName()+".bmp");              byte[] buf = new byte[1024];              int len = 0;              while ((len = in.read(buf)) != -1) {                  fos.write(buf0len);                  fos.flush();              }              fos.close();              s.close();          } catch (FileNotFoundException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }      }  }  

六、浏览器客户端--自定义服务器

import java.io.*;  import java.net.*;    public class ServerDemo {      public static void main(String[] argsthrows IOException{          ServerSocket ss = new ServerSocket(40000);          while(true){              Socket s = ss.accept();              OutputStream outs = s.getOutputStream();              outs.write("<html><font color='red' size='7' >hello ! I'm ok !</font></html>".getBytes());              outs.close();              s.close();          }      }  }  

 ---------------------- android培训、java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima