----------------------android培训、java培训、期待与您交流! ----------------------
一:InetAddress类:
InetAddress类在网络API套接字编程中扮演了一个重要角色。
由于InetAddress类只有一个构造函数,而且不能传递参数,所以不能直接创建InetAddress对象,比如下面的做法就是错误的:
InetAddressia = new InetAddress ();
但我们可以通过下面的方法创建来创建一个InetAddress对象或InetAddress数组:
. getAllByName(String host)方法返回一个InetAddress对象的引用,每个对象包含一个表示相应主机名的单独的IP地址,这个IP地址是通过host参数传递的,对于指定的主机如果没有IP地址存在那么这个方法将抛出一个UnknownHostException异常对象。
. getByAddress(byte [] addr)方法返回一个InetAddress对象的引用,这个对象包含了一个Ipv4地址或Ipv6地址,Ipv4地址是一个4字节数组,Ipv6地址是一个16字节地址数组,如果返回的数组既不是4字节的也不是16字节的,那么方法将会抛出一个UnknownHostException异常对象。
. getByAddress(String host, byte []addr)方法返回一个InetAddress对象的引用,这个InetAddress对象包含了一个由host和4字节的addr数组指定的IP地址,或者是host和16字节的addr数组指定的IP地址,如果这个数组既不是4字节的也不是16位字节的,那么该方法将抛出一个UnknownHostException异常对象。
. getByName(String host)方法返回一个InetAddress对象,该对象包含了一个与host参数指定的主机相对应的IP地址,对于指定的主机如果没有IP地址存在,那么方法将抛出一个UnknownHostException异常对象。
. getLocalHost()方法返回一个InetAddress对象,这个对象包含了本地机的IP地址,考虑到本地主机既是客户程序主机又是服务器程序主机,为避免混乱,我们将客户程序主机称为客户主机,将服务器程序主机称为服务器主机。
1:获取网络中的主机域名和ip地址
try {
// InetAddressia=InetAddress.getByName("MICROSOF-F92F47");
InetAddressia=InetAddress.getByName("192.168.1.2");
// InetAddressia=InetAddress.getLocalHost();
System.out.println(ia.getHostName());
System.out.println(ia.toString());
} catch(UnknownHostException e) {
// TODOAuto-generated catch block
e.printStackTrace();
}
二:网络编程类
UDP通信
DatagramSocket
DatagramPacket
TCP通信
ServerSocket: 服务器
Socket:客户端类
三:ServerSocket类
1:ServerSocket类用来表示服务器套接字。服务器套接字通过指定的端口来等待连接的套接字,他的主要功能是等待来自网络上的连接“请求”。服务器套接字一次可以与一个套接字连接,如果多台客户机同时提出连接请求,服务器套接字会将请求连接的客户机存入队列中,然后从中取出一个套接字,与服务器新建的套接字连接起来,如果请求连接数大于最大容纳数,则多出的请求被拒绝。队列的默认大小为50.
2:ServerSocket类的构造方法:
ServerSocket() |
ServerSocket(int port) |
ServerSocket(int port, int backlog) Backlog:指定队列的最大长度。 |
3:
方法摘要 | |
accept() | |
void | bind(SocketAddress endpoint) |
void | bind(SocketAddress endpoint, int backlog) |
void | close() |
getInetAddress() | |
int | getLocalPort() |
boolean | isBound() |
boolean | isClosed() |
toString() |
4:调用ServerSocket类的accept()方法会返回一个和客户端Socket对象连接的Socket对象。
5:服务器端的Socket对象使用getOutputStream()方法获得的输出流将指向客户端Socket对象使用getInputStream()方法获得的那个输入流。反之也成立。
也就是说:当服务器端向输出流写入信息时,客户端通过相应的输入流就能读取;反之也成立。
6:创建一个服务器套接字:
publicstaticvoid main(String[] args) {
// TODO Auto-generatedmethod stub
try {
ServerSocket s=newServerSocket(9999);
System.out.println("成功创建服务器套接字");
while(true){
System.out.println("等待客户端的连接...");
Socketso=s.accept();
System.out.println("与客户端建立连接");
}
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
四:Socket类
1:Socket类是套接字类。使用Socket类时需要制定待连接的服务器的ip和端口号。服务器套接字与客户端套接字连接成功后,则可以获取套接字的输入输出流,进行数据交换。
2:构造方法:
构造方法摘要 | |
| Socket() |
| Socket(InetAddress address, int port) |
| |
| Socket(String host, int port, InetAddress localAddr, int localPort) |
host用于指定服务器的ip地址,port是连接服务器的端口号。
五:例:客户端和服务器端的连接:
1:服务器端:
publicclassHelloServer {
//可以使用telnet进行测试:openlocalhost 9999
publicstaticvoid main(String[] args)throwsIOException {
//实例化一个服务器端的socket连接
ServerSocketss=newServerSocket(9999);
//用于向客户端打印输出
PrintWriter out=null;
//实例化一个客户端对象,用于接收客户端的连接
Socket cs=null;
System.out.println("等待客户端连接...");
//通过ServerSocket类中的accept()方法,
//接收客户端的请求,此方法返回一个客户端的Socket请求
cs=ss.accept();
//out就具备了向cs打印的功能
out=newPrintWriter(cs.getOutputStream(),true);
out.println("Hello world");
cs.close();
ss.close();
}
}
客户端:
publicclassHelloClient {
publicstaticvoid main(String[] args)throwsUnknownHostException,IOException {
//实例化一个Socket对象,在本机的9999端口进行监听
Socket cs=newSocket("localhost",9999);
//次对象用于读取服务器端发送过来的数据
BufferedReader in=null;
//用来将输入输出流与socket关联
//getInputStream()返回此对象的输入流;然后把输入流转化为字符流
in=newBufferedReader(newInputStreamReader(cs.getInputStream()));
System.out.println(in.readLine());
in.close();
cs.close();
}
}
例2:服务器端:
import java.io.*;
import java.net.*;
publicclassEchoServer {
publicstaticvoid main(String[] args)throwsIOException {
ServerSocketserverSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//实例化监听端口
serverSocket =newServerSocket(1111);
} catch (IOException e) {
System.err.println("Could notlisten on port: 1111.");
System.exit(1);
}
Socket incoming = null;
while (true) {
incoming = serverSocket.accept();
out =newPrintWriter(incoming.getOutputStream(),true);
//将字节流放入字符流缓冲之中
in =newBufferedReader(newInputStreamReader(
incoming.getInputStream()));
//提示信息
out.println("Hello! . .. ");
out.println("Enter BYEto exit");
out.flush();
//在没有异常的情况下不断循环
while (true) {
//只有当有用户输入数据的时候才返回数据内容
String str = in.readLine();
//当用户连接断掉时会返回空值null
if (str ==null) {
//退出循环
break;
}else {
//对用户输入字串加前缀Echo:,将此信息打印到客户端
out.println("Echo: " + str);
out.flush();
//退出命令,equalsIgnoreCase()是不区分大小写的比较
if (str.trim().equalsIgnoreCase("BYE"))
break;
}
}
//收尾工作
out.close();
in.close();
incoming.close();
serverSocket.close();
}
}
}
客户端:
importjava.io.*;
importjava.net.*;
publicclass EchoClient
{
publicstatic void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriterout = null;
BufferedReader in = null;
try
{
echoSocket= new Socket ( "localhost", 1111);
out= new PrintWriter(echoSocket.getOutputStream(), true);
in= new BufferedReader(
newInputStreamReader(echoSocket.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.println("Don'tknow about host: localhost.");
System.exit(1);
}
System.out.println(in.readLine());
System.out.println(in.readLine());
BufferedReaderstdIn =
newBufferedReader(newInputStreamReader(System.in));
String userInput;
//将客户端Socket输入流输出到标准输出
while ((userInput =stdIn.readLine()) != null)
{
out.println(userInput);
System.out.println(in.readLine());
}
out.close();
in.close();
echoSocket.close();
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net/heima