------- android培训、java培训、期待与您交流! ----------
16.TCP客户端程序
编程实例:编写一个与上面的服务器程序通信的客户端程序。
要点:连接服务器的IP地址和端口号不要固定编写在程序代码中,而是通过程序的运行时的参数来指导,以提供较好的灵活性和较高的通用性。
public class TcpClient {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
// TODO Auto-generatedmethod stub
if(args.length < 2){
System.out.println("Usage:javaTcpClient ServerIP ServerPort");
return;
}
Socket s = new Socket(args[0],
Integer.parseInt(args[1]));
InputStream ips = s.getInputStream();
OutputStream ops = s.getOutputStream();
BufferedReader brNet = new BufferedReader(
new InputStreamReader(ips));
PrintWriter pw = new PrintWriter(ops,true);
BufferedReader brKeyBoard = new BufferedReader(
new InputStreamReader(System.in));
while(true){
String strWord = brKeyBoard.readLine();
pw.println(strWord);
if(strWord.equalsIgnoreCase("quit")){
break;
}
System.out.println(brNet.readLine());
}
pw.close();
brNet.close();
brKeyBoard.close();
s.close();
}
}
17.在TCP网络连接上传递对象
a) ObjectInputStream和ObjectOutputStream可以从底层输入流中读取对象类型的数据和将对象类型的数据写入到底层输出流。
b) 使用ObjectInputStream和ObjectOutputStream来包装底层网络字节流,TCP服务器和TCP客户端之间就可以传递对象类型的数据
c) 编程实例:通过网络传输Java对象。
Student:
public class Student implements Serializable{
int id;
String name;
int age;
String department;
public Student(int id, String name,int age, String department) {
this.id = id;
this.name = name;
this.age = age;
this.department = department;
}
@Override
public String toString() {
// TODO Auto-generatedmethod stub
return"id=" + id +",name=" + name +",age=" + age +",department=" + department;
}
}
ObjectClient:
public class ObjectClient {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
// TODO Auto-generatedmethod stub
Socket s = new Socket("111.167.84.164",8001);
InputStream ips = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(ips);
Student stu = (Student)ois.readObject();
System.out.println(stu.toString());
ois.close();
s.close();
}
}
ObjectServer:
public class ObjectServer {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
// TODO Auto-generatedmethod stub
ServerSocket ss = new ServerSocket(8001);
Socket s = ss.accept();
OutputStream ops = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(ops);
Student stu = new Student(20,"zhangsan", 22, "wuli");
oos.writeObject(stu);
oos.close();
s.close();
ss.close();
}
}
18.访问Internet网络资源
Java.net包中还有URL、URLDecoder、URLEncoder、URLConnection、HttpURLConnection等类。
19.URL
a)URL的基本组成:协议、主机名、端口号、资源名
例如,http://www.it315.org:8080/index.html
b)相对URL,例如”/a.html”、”./a.html”、”../../a.html”、”a.html”
c)URL编码规则:
1.将空格转换为加号(+).
2.对0-9,a-z,A-Z之间的字符保持不变。
3.对于所有其他的字符,用这个字符的当前字符集编码在内存中的十六进制格式表示,并在每个字符前加上一个百分号(%)。如字符”+”用%2B表示,字符”=”用%3D表示,字符”&”用%26表示,每个中文字符在内存中占两个字符,字符”中”用%6D%D0表示,字符”国”用%B9%FA表示
4.对于空格也可以直接使用其十六进制编码方式,即用%20表示,而不是将它转换成加号(+)。
d)java.net包中提供了URLEncorder和URLDecoder这两个类,来实现URL编码和解码。
20.HTTP协议的会话过程

21.HTTP请求消息
一个完整的请求消息包括:一个请求行、若干消息头、以及实体内容。

22.HTTP响应消息
一个完整的响应消息包括:一个请求行、若干消息头、以及实体内容。

23.了解几个HTTP消息头
a) Connection:用于指定处理完本次请求/响应后,客户端与服务器是否继续保持连接。设置值可以为Keep-Alive和close。
b) Accept-Language:用于指出客户机期望服务器返回的文档所使用的国家语言,可以指定多个以逗号分隔的国家语言
c) Content-Length:用于表示实体内容的长度(字节数)。
d) Range:用于指定服务器只需返回文档中的部分内容及内容范围,有以下几种使用格式:
1. Range:bytes=100-599
2. Range:bytes=100-
3. Range:bytes=-100
e) Content-Range:用于指定服务器返回的部分实体内容的位置信息,例如,
Content-Range:bytes 2543-4532/7898
24.URL类
a) 构造函数(都可以引发MalformedURLException异常):
1. public URL(String spec)
2. public URL(String protocol,Stringhost,int port,String file)
3. public URL(String protocol,Stringhost,int port,String file,URLStreamHandler handler)
4. public URL(URL context,Stringspec)
b) getProtocol、getHost、getPort、getFile等方法
c) openConnection方法返回URLConnetion对象。
25.工厂设计模式
a) URL类的setURLStreamHandlerFactory(URLStreamHandlerFactory fac)静态方法。
b) URLStreamHandlerFactory类的createURLStreamHandler(Stringprotocol)方法
c) 工程模式的工作原理

26.URLConnection与HttpURLConnection类
a) URLConnection与HttpURLConnection的作用
b) URLConnection的连接过程
c) setRequestProperty方法
d) getHeaderFields方法
e) getInputStream和getOutputStream方法
f) getHeadeField、getContentLength、getContentEncoding、getContentType等方法
g) 一个HTTP连接可以被多个HttpURLConnection实例对象共享,调用HttpURLConnection的disconnect方法可以关闭底层共享网络。
编程实例:将访问www.google.com站点的HTTP请求消息的Accept-Language头分别设置成日文和中文后,然后打印出www.google.com站点返回的所有响应消息头和网页内容
public class GetGoogle {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
// TODO Auto-generatedmethod stub
System.out.println("获取中文页面");
getContentByLanguage("zh-cn");
System.out.println("\n获取日文页面");
getContentByLanguage("ja");
}
public static void getContentByLanguage(String country)throws Exception{
URL urlGoogle = new URL("http://www.baidu.com");
HttpURLConnection googleConnection =(HttpURLConnection)urlGoogle.openConnection();
googleConnection.setRequestProperty("Accept-language",country);
Map requests = googleConnection.getRequestProperties();
Set reqFields = requests.keySet();
Iterator itrReq = reqFields.iterator();
while(itrReq.hasNext()){
String field = (String)itrReq.next();
System.out.println(field +":" +
googleConnection.getRequestProperty(field));
}
googleConnection.connect();
Map responses = googleConnection.getHeaderFields();
Set resFields = responses.keySet();
Iterator itrRes = resFields.iterator();
while(itrRes.hasNext()){
String field = (String)itrRes.next();
System.out.println(field +":" +
googleConnection.getRequestProperty(field));
}
InputStream is = googleConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String strLine = null;
while((strLine =br.readLine()) !=null){
System.out.println(strLine);
}
br.close();
googleConnection.disconnect();
}
}
本文介绍了TCP客户端程序的设计与实现,重点讲解了如何通过Java进行网络通信,并演示了对象在网络间的传递。此外,还详细解释了如何使用Java访问Internet资源,包括URL的构成与编码规则、HTTP协议的基础知识。
1084

被折叠的 条评论
为什么被折叠?



