java网络编程简介

1.host

任何一个可以上网的设备都是一个host
host包括ip地址 主机名字和域名

ip地址

唯一指定网络上的一台机器(世界级的身份证号)
ipv4 ipv6

主机名字

多用在本地,局域网内(姓名,一个区域内唯一)

域名

多用在世界级别的(江苏省南京市一样的)

2.网络连接的两种角色

服务端和客户端

服务端的端口: 如223.3.68.116:8080中的8080
一个服务器可能拥有很多服务的时候用于分辨服务类型
0~1023被征用为系统专用的

3.连接

建立在两个host两个端口的之间的联系
连接

4.java网络编程

java。net.*

InetAddress简介

  1. Abstraction of a network address
  2. Allows an address to be obtained from a host name and vice versa
  3. Is immutable (is a read-only object)

Static construction and using( using a factory method ) 
InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取,有以下的方法:

static InetAddress[] getAllByName(String host)
static InetAddress getByAddress(byte[] addr)
static InetAddress getByAddress(String host,byte[] addr)
static InetAddress getByName(String host)
static InetAddress getLocalHost()

InetAddress address=InetAddress.getByName("www.baidu.com");

Some useful methods:

  • String getHostName() //Gives you the host name (for example “www.sun.com”)
  • String getHostAddress()//Gives you the address (for example “192.18.97.241”)
  • InetAddress getLocalHost()
  • InetAddress[] getAllByName(String hostName)

InetAddress简介

Socket

Two Types of Socket

ServerSocket

java.net.ServerSocket (is used by servers so that they can accept incoming connections)

A server is a piece of software which advertises
and then provides some service on request 
Listens on well-known port for incoming connections
Creates a dynamically allocated Socket for each newly established connection
Maintains a queue to ensure that prospective clients are not lost
Construction:

ServerSocket(int port, int backlog) Allows up to backlog requests to queue waiting 
for the server to deal with them

*some useful methods:

Socket accept() //Blocks waiting for a client to attempt to establish a connection
void close() //Called by the server when it is shutting down to ensure that any resources are
deallocated

java.net.Socket (is used by clients who wish to establish a connection to a (remote) server)

A client is a piece of software (usually on a different machine) which makes use of some service

Socket

Provides access to network streams Bi-directional communication between sender and
receiver
Can be used to connect to a remote address and port
*constructor:

Socket(String remoteHost, int port)//Also used to accept an incoming connection (see
ServerSocket)

posted @ 2013-12-23 20:45  金发萌音  阅读(173)  评论(0编辑  收藏  举报