JAVA网络编程
一个是如何准确的定位网络上一台或多台主机,另一个就是找到主机后如何可靠高效的进行数据传输。
在TCP/IP协议中IP层主要负责网络主机的定位,数据传输的路由,由IP地址可以唯一地确定Internet上的一台主机。
而TCP层则提供面向应用的可靠(tcp)的或非可靠(UDP)的数据传输机制,这是网络编程的主要对象,一般不需要关心IP层是如何处理数据的。
目前较为流行的网络编程模型是客户机/服务器(C/S)结构。即通信双方一方作为服务器等待客户提出请求并予以响应。客户则在需要服务时向服务器提 出申请。服务器一般作为守护进程始终运行,监听网络端口,一旦有客户请求,就会启动一个服务进程来响应该客户,同时自己继续监听服务端口,使后来的客户也 能及时得到服务。
二,两类传输协议:TCP;UDP
TCP是Tranfer Control Protocol的 简称,是一种面向连接的保证可靠传输的协议。通过TCP协议传输,得到的是一个顺序的无差错的数据流。发送方和接收方的成对的两个socket之间必须建 立连接,以便在TCP协议的基础上进行通信,当一个socket(通常都是server socket)等待建立连接时,另一个socket可以要求进行连接,一旦这两个socket连接起来,它们就可以进行双向数据传输,双方都可以进行发送 或接收操作。
UDP是User Datagram Protocol的简称,是一种无连接的协议,每个数据报都是一个独立的信息,包括完整的源地址或目的地址,它在网络上以任何可能的路径传往目的地,因此能否到达目的地,到达目的地的时间以及内容的正确性都是不能被保证的。
比较:
UDP:1,每个数据报中都给出了完整的地址信息,因此无需要建立发送方和接收方的连接。
2,UDP传输数据时是有大小限制的,每个被传输的数据报必须限定在64KB之内。
3,UDP是一个不可靠的协议,发送方所发送的数据报并不一定以相同的次序到达接收方
TCP:1,面向连接的协议,在socket之间进行数据传输之前必然要建立连接,所以在TCP中需要连接
时间。
2,TCP传输数据大小限制,一旦连接建立起来,双方的socket就可以按统一的格式传输大的
数据。
3,TCP是一个可靠的协议,它确保接收方完全正确地获取发送方所发送的全部数据。
应用:
1,TCP在网络通信上有极强的生命力,例如远程连接(Telnet)和文件传输(FTP)都需要不定长度的数据被可靠地传输。但是可靠的传输是要付出代价的,对数据内容正确性的检验必然占用计算机的处理时间和网络的带宽,因此TCP传输的效率不如UDP高。
2,UDP操作简单,而且仅需要较少的监护,因此通常用于局域网高可靠性的分散系统中client/server应用程序。例如视频会议系统,并不要求音频视频数据绝对的正确,只要保证连贯性就可以了,这种情况下显然使用UDP会更合理一些。
三,基于Socket的java网络编程
1,什么是Socket
网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket。Socket通常用来实现客户方和服务方的连接。Socket是TCP/IP协议的一个十分流行的编程界面,一个Socket由一个IP地址和一个端口号唯一确定。
但是,Socket所支持的协议种类也不光TCP/IP一种,因此两者之间是没有必然联系的。在Java环境下,Socket编程主要是指基于TCP/IP协议的网络编程。
2,Socket通讯的过程
Server端Listen(监听)某个端口是否有连接请求,Client端向Server 端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client 端都可以通过Send,Write等方法与对方通信。
对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:
(1) 创建Socket;
(2) 打开连接到Socket的输入/出流;
(3) 按照一定的协议对Socket进行读/写操作;
(4) 关闭Socket.(在实际应用中,并未使用到显示的close,虽然很多文章都推荐如此,不过在我的程序中,可能因为程序本身比较简单,要求不高,所以并未造成什么影响。)
3,创建Socket
创建Socket
java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用很方便。其构造方法如下:
Socket(InetAddress address, int port);
Socket(InetAddress address, int port, boolean stream);
Socket(String host, int prot);
Socket(String host, int prot, boolean stream);
Socket(SocketImpl impl)
Socket(String host, int port, InetAddress localAddr, int localPort)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog, InetAddress bindAddr)
其中address、host和port分别是双向连接中另一方的IP地址、主机名和端 口号,stream指明socket是流socket还是数据报socket,localPort表示本地主机的端口号,
localAddr和 bindAddr是本地机器的地址(ServerSocket的主机地址),impl是socket的父类,既可以用来创建serverSocket又可 以用来创建Socket。count则表示服务端所能支持的最大连接数。
例如:学习视频网 http://www.xxspw.com
Socket client = new Socket("127.0.01.", 80);
ServerSocket server = new ServerSocket(80);
注意,在选择端口时,必须小心。每一个端口提供一种特定的服务,只有给出正确的端口,才 能获得相应的服务。0~1023的端口号为系统所保留,
例如http服务的端口号为80,telnet服务的端口号为21,ftp服务的端口号为23, 所以我们在选择端口号时,最好选择一个大于1023的数以防止发生冲突。
在创建socket时如果发生错误,将产生IOException,在程序中必须对之作出处理。所以在创建Socket或ServerSocket是必须捕获或抛出例外。
4,简单的Client/Server程序
1. 客户端程序
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
//向本机的4700端口发出客户请求
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
String readline;
readline=sin.readLine(); //从系统标准输入读入一字符串
while(!readline.equals("bye")){
//若从标准输入读入的字符串为 "bye"则停止循环
os.println(readline);
//将从系统标准输入读入的字符串输出到Server
os.flush();
//刷新输出流,使Server马上收到该字符串
System.out.println("Client:"+readline);
//在系统标准输出上打印读入的字符串
System.out.println("Server:"+is.readLine());
//从Server读入一字符串,并打印到标准输出上
readline=sin.readLine(); //从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e); //出错,则打印出错信息
}
}
}
2. 服务器端程序
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
//创建一个ServerSocket在端口4700监听客户请求
}catch(Exception e) {
System.out.println("can not listen to:"+e);
//出错,打印出错信息
}
Socket socket=null;
try{
socket=server.accept();
//使用accept()阻塞等待客户请求,有客户
//请求到来则产生一个Socket对象,并继续执行
}catch(Exception e) {
System.out.println("Error."+e);
//出错,打印出错信息
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
PrintWriter os=newPrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
System.out.println("Client:"+is.readLine());
//在标准输出上打印从客户端读入的字符串
line=sin.readLine();
//从标准输入读入一字符串
while(!line.equals("bye")){
//如果该字符串为 "bye",则停止循环
os.println(line);
//向客户端输出该字符串
os.flush();
//刷新输出流,使Client马上收到该字符串
System.out.println("Server:"+line);
//在系统标准输出上打印读入的字符串
System.out.println("Client:"+is.readLine());
//从Client读入一字符串,并打印到标准输出上
line=sin.readLine();
//从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
server.close(); //关闭ServerSocket
}catch(Exception e){
System.out.println("Error:"+e);
//出错,打印出错信息
}
}
}
5,支持多客户的client/server程序
前面的Client/Server程序只能实现Server和一个客户的对话。在实际应用 中,往往是在服务器上运行一个永久的程序,它可以接收来自其他多个客户端的请求,提供相应的服务。
为了实现在服务器方给多个客户提供服务的功能,需要对上 面的程序进行改造,利用多线程实现多客户机制。
服务器总是在指定的端口上监听是否有客户请求,一旦监听到客户请求,服务器就会启动一个专门的服务线程来响 应该客户的请求,而服务器本身在启动完线程之后马上又进入监听状态,等待下一个客户的到来。
6、UDP的实现
主要用到两个类DatagramPacket和DatagramSocket
DatagramSocket:
此类表示用来发送和接收数据报包的套接字
数据报套接字是包投递服务的发送或接收点。每个在数据报套接字上发送或接收的包都是单独编址和路由的。从一台机器发送到另一台机器的多个包可能选择不同的路由,也可能按不同的顺序到达。
在 DatagramSocket 上总是启用 UDP 广播发送。为了接收广播包,应该将 DatagramSocket 绑定到通配符地址。在某些实现中,将 DatagramSocket 绑定到一个更加具体的地址时广播包也可以被接收
DatagramPacket:
此类表示数据报包。
数据报包用来实现无连接包投递服务。每条报文仅根据该包中包含的信息从一台机器路由到另一台机器。
从一台机器发送到另一台机器的多个包可能选择不同的路由,也可能按不同的顺序到达。
不对包投递做出保证。

代码示例:
服务端:
public static void createServerUDP(int port) throws IOException {
/*
* 接收客户端发送的数据
*/
// 1.创建服务器端DatagramSocket,指定端口
DatagramSocket socket = new DatagramSocket(port);
// 2.创建数据报,用于接收客户端发送的数据
byte[] data = new byte[1024];// 创建字节数组,指定接收的数据包的大小
DatagramPacket packet = new DatagramPacket(data, data.length);
// 3.接收客户端发送的数据
System.out.println("****服务器端已经启动,等待客户端发送数据");
socket.receive(packet);// 此方法在接收到数据报之前会一直阻塞
// 4.读取数据
String info = new String(data, 0, packet.getLength());
System.out.println("我是服务器,客户端说:" + info);
/*
* 向客户端响应数据
*/
// 1.定义客户端的地址、端口号、数据
InetAddress address = packet.getAddress();
int clientPort = packet.getPort();
byte[] data2 = "欢迎您!".getBytes();
// 2.创建数据报,包含响应的数据信息
DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, clientPort);
// 3.响应客户端
socket.send(packet2);
// 4.关闭资源
socket.close();
}
客户端:
public static void clientUDP(String ip,int port) throws IOException {
/*
* 向服务器端发送数据
*/
// 1.定义服务器的地址、端口号、数据
InetAddress address = InetAddress.getByName(ip);
byte[] data = "用户名:admin;密码:123".getBytes();
// 2.创建数据报,包含发送的数据信息
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
// 3.创建DatagramSocket对象
DatagramSocket socket = new DatagramSocket();
// 4.向服务器端发送数据报
socket.send(packet);
/*
* 接收服务器端响应的数据
*/
// 1.创建数据报,用于接收服务器端响应的数据
byte[] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
// 2.接收服务器响应的数据
socket.receive(packet2);
// 3.读取数据
String reply = new String(data2, 0, packet2.getLength());
System.out.println("我是客户端,服务器说:" + reply);
// 4.关闭资源
socket.close();
}
7、TCP的长连接
//设置为长连接,服务端判断有此参数就不关闭连接。
httppost.setHeader("Connection", "Keep-Alive");
HTTP协议等编程:
1、基于JDK的实现
代码示例:
public static byte[] sendMessage(String mes, String httpUrl,String type) {
try {
URL url = new URL(httpUrl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(type); // 设置请求方式
connection.setRequestProperty("Content-Length", String.valueOf(mes.length())); // 设置接收数据的格式
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "UTF-8"); // utf-8编码
if (mes != null) {
out.append(mes);
}
out.flush();
out.close();
// 读取响应
int retCode = connection.getResponseCode();
InputStream is = null;
if(retCode >= 400) {
is = connection.getErrorStream();
}
else {
is = connection.getInputStream();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteBuffer src;
int readLen = 512;
byte[] temp = new byte[readLen];
byte[] data = new byte[0];
while(bis.available() > readLen) {
bis.read(temp);
data = ByteUtil.byteMerger(data,temp);
}
// 处理不足512的剩余部分
int remain = bis.available();
byte[] last = new byte[remain];
bis.read(last);
data = ByteUtil.byteMerger(data,last);
bis.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2、基于Apache的实现
common-httpclient 的工具包的实现
- /**
- * HttpClient连接SSL
- */
- public void ssl() {
- CloseableHttpClient httpclient = null;
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
- try {
- // 加载keyStore d:\\tomcat.keystore
- trustStore.load(instream, "123456".toCharArray());
- } catch (CertificateException e) {
- e.printStackTrace();
- } finally {
- try {
- instream.close();
- } catch (Exception ignore) {
- }
- }
- // 相信自己的CA和所有自签名的证书
- SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
- // 只允许使用TLSv1协议
- SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
- SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
- httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
- // 创建http请求(get方式)
- HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
- System.out.println("executing request" + httpget.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- HttpEntity entity = response.getEntity();
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- if (entity != null) {
- System.out.println("Response content length: " + entity.getContentLength());
- System.out.println(EntityUtils.toString(entity));
- EntityUtils.consume(entity);
- }
- } finally {
- response.close();
- }
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (KeyManagementException e) {
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (KeyStoreException e) {
- e.printStackTrace();
- } finally {
- if (httpclient != null) {
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * post方式提交表单(模拟用户登录请求)
- */
- public void postForm() {
- // 创建默认的httpClient实例.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- // 创建httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- // 创建参数队列
- List<namevaluepair> formparams = new ArrayList<namevaluepair>();
- formparams.add(new BasicNameValuePair("username", "admin"));
- formparams.add(new BasicNameValuePair("password", "123456"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
- System.out.println("--------------------------------------");
- }
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
- */
- public void post() {
- // 创建默认的httpClient实例.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- // 创建httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- // 创建参数队列
- List<namevaluepair> formparams = new ArrayList<namevaluepair>();
- formparams.add(new BasicNameValuePair("type", "house"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
- System.out.println("--------------------------------------");
- }
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 发送 get请求
- */
- public void get() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- // 创建httpget.
- HttpGet httpget = new HttpGet("http://www.baidu.com/");
- System.out.println("executing request " + httpget.getURI());
- // 执行get请求.
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- System.out.println("--------------------------------------");
- // 打印响应状态
- System.out.println(response.getStatusLine());
- if (entity != null) {
- // 打印响应内容长度
- System.out.println("Response content length: " + entity.getContentLength());
- // 打印响应内容
- System.out.println("Response content: " + EntityUtils.toString(entity));
- }
- System.out.println("------------------------------------");
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 上传文件
- */
- public void upload() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
- FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
- StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
- HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
- httppost.setEntity(reqEntity);
- System.out.println("executing request " + httppost.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- HttpEntity resEntity = response.getEntity();
- if (resEntity != null) {
- System.out.println("Response content length: " + resEntity.getContentLength());
- }
- EntityUtils.consume(resEntity);
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
以上实例是采用HttpClient4.3最新版本
3.x的实例如下:
private void httpReq(String url) {
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(url);
int statusCode = client.executeMethod(get);
byte[] resultByte = get.getResponseBody();
get.releaseConnection();
System.out.println(statusCode);
System.out.println(new String(resultByte,"UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void testLoginHttp() {
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(homeUrl);
client.executeMethod(get);
get.releaseConnection();
PostMethod post = new PostMethod(loginUrl);
NameValuePair username = new NameValuePair("j_username", "zyifeng");
NameValuePair password = new NameValuePair("j_password", "kingold201511");
NameValuePair domainName = new NameValuePair("DOMAIN_NAME", "KINGOLD");
NameValuePair logonDomainName = new NameValuePair("logonDomainName", "KINGOLD");
NameValuePair domain = new NameValuePair("domain", "1");
post.setRequestBody(new NameValuePair[]{username, password,domainName,logonDomainName,domain});
client.executeMethod(post);
System.out.println(post.getStatusLine());
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
get的请求的中文参数要经过编码
String contentUtf = URLEncoder.encode(Content,"UTf-8");
JAVA实现http的get和post:
http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html
获取客户端IP
http://www.cnblogs.com/ITtangtang/p/3927768.html

浙公网安备 33010602011771号