------- android培训、java培训、期待与您交流! ----------
网络编程(一)
1. 网络编程的基础编程知识
a) 网络协议与TCP/IP
b) IP地址和Port(端口号)
i. 本地回路的IP地址:127.0.0.1
ii. 端口号的范围为0~65535之间,0~1023之间的端口数是用于一些知名的网络服务和应用。
c) UDP与TCP
i. TCP,传输控制协议,是面向连接的通信协议
ii. UDP,用户数据报协议,是无连接通信协议
iii.
2. Socket
a) Socket是网络驱动层提供给应用程序编程的接口和一种机制
b) 可以把Socket比喻成是一个港口码头。应用程序只要把货物放在港口码头上,就算完成了货物的运送。应用程序志向等待货物到达码头后,将货物取走。
c) Socket在应用程序中创建,通过一种绑定机制与驱动程序建立关系,告诉自己所对应的IP和Port。
d) Socket数据发送过程
e) Socket数据接收过程
3.java中的网络编程类
f) 位于java.net包中
g) DatagramSocket类用于UDP通信
h) ServerSocket类用于TCP通信的服务器端
i) Socket类用于TCP通信的服务器和客户端
j) DatagramSocket类
4.UDP网络程序
i. 构造函数
1. public DatagramSocket()
2. public DatagramSocket(int port)
3. public DatagramSocket(intport,InetAddress laddr)
ii. close方法
iii. send(DatagramPacket p)方法
iv. receive(DatagramPacket p)方法
5.DatagramPaket类
如果把DatagramSocket比作创建的港口码头,那么DatagramSocket就是发送和接收数据的集装箱。
public DatagramPacket(byte[] buf,int length)
public DatagramPacket(byte[] buf,intlength,IntAddress address,int port)
getInetAddress和getPort方法
getData和getLength方法
6.InetAddress类
a)InetAddress是用于表示计算机IP地址的一个类,而在日常应用中的计算机地址是用”192.168.0.0”、www.it315.org等字符串格式来表示的。
b)getByName方法
c)getHostAddress方法
7.最简单的UDP程序、
a)字符串与字节数组之间的双向转换。
b)UDP接收程序必须先启动运行,才能接收UDP发送程序发送的数据
c) 用start命令来打开新命令行窗口的好处
d)解决发送中午字符串的问题
8.用UDP编写网络聊天程序
a) 编写图形用户界面
b) 编写网络消息发送功能
c) 编写网络消息接收功能
注:只有UDP能发送和接受广播
public class Chat extends Frame {
List lst = new List(6);
TextField tfIP = new TextField(15);
TextField tfData = new TextField(20);
DatagramSocket ds = null;
public static void main(String args[]){
System.out.println("StartingChat... ");
Chat mainFrame = new Chat();
mainFrame.setSize(300, 400);
mainFrame.setTitle("Chat");
mainFrame.setVisible(true);
mainFrame.setResizable(false);
}
public Chat(){
try {
ds = new DatagramSocket(3000);
} catch (SocketException e1) {
// TODO Auto-generatedcatch block
e1.printStackTrace();
}
this.add(lst,"Center");
Panel p = new Panel();
this.add(p,"South");
p.setLayout(new BorderLayout());
p.add(tfIP,"West");
p.add(tfData,"East");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generatedmethod stub
byte[] buf =new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
while(true){
try {
ds.receive(dp);
} catch (IOException e) {
// TODO Auto-generatedcatch block
if(!ds.isClosed()){
e.printStackTrace();
}
}
lst.add(new String(buf, 0, dp.getLength()) +
"from" + dp.getAddress().getHostAddress() +":" +dp.getPort(), 0);
}
}
}).start();
tfData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
byte[] buf;
buf = tfData.getText().getBytes();
DatagramPacket dp;
try {
dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName(tfIP.getText()),3000);
ds.send(dp);
} catch (Exception e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
tfData.setText("");
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
ds.close();
disable();
System.exit(0);
}
});
}
}
9.私有IP通过网关代理上网的原理
映射表有一定时效性
10.TCP网络程序
a)TCP网络程序的工作原理
1.服务器程序创建一个ServerSocket,然后调用accept方法等待客户来连接
2.客户端程序创建一个Socket并请求与服务器建立连接。
3.服务器接收客户的连接请求,并创建一个新的Socket与该客户建立专线连接
4.建立了连接的两个Socket的一个单独的线程(由服务器程序创建)上的对话
5. 服务器开始等待新的连接请求,当新的连接请求到达时,重复2到步骤5的过程
11.ServerSocket
a) 构造函数
1.public ServerSocket()
2.public ServerSocket(int port)
3.public ServerSocket(int port,int backlog)
4.public ServerSocket(int port,int backlog,InetAddress bindAddr)
b) close方法
c) accept方法
12.Socket
a) 构造函数
1.public Socket()
2.public Socket(String host,int port)
3.public Socket(InetAddress address,int port)
4.public Socket(String host,int port,InetAddress localAddr,int localPort)
5.public Socekt(InetAddress address,int port,InetAddress localAddr,int localPort)
getInputStream和getOutputStream方法
13.简单的TCP服务器程序
a)TCP服务器程序必须先启动运行,TCP客户程序才能连接上TCP服务器
b)使用Windows提供的telnet程序测试TCP服务器程序
c)使用BufferedReader包装类,从网络输入流中一次读取一行文本
d)如何打开telnet程序的本地回显功能。
public class TcpService {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generatedmethod stub
ServerSocket ss;
try {
ss = new ServerSocket(8001);
Socket s = ss.accept();
InputStream ips = s.getInputStream();
OutputStream ops = s.getOutputStream();
ops.write("welcome tohello\n".getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(ips));
System.out.println(br.readLine());
/* byte[] buf = new byte[1024];
int len = ips.read(buf);
System.out.println(new String(buf,0,len));
*/
ips.close();
ops.close();
br.close();
s.close();
ss.close();
} catch (Exception e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
14.完善的TCP服务器程序模型
编程实例:服务器程序能够同时与多个客户端会话,客户端每次向服务器发送一行字符文本,服务器就将这行字符文本中的所有字符反向排列后送回客户端,当客户端向服务器发送的一行文本内容为”quit”时,服务器结束与客户端的会话。
ReverseServer:
public class ReverseServer {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
// TODO Auto-generatedmethod stub
ServerSocket ss = null;
if(args.length < 1){
ss = new ServerSocket(8001);
}else{
ss = new ServerSocket(Integer.parseInt(args[0]));
}
boolean bRunning =true;
while(bRunning){
Socket s = ss.accept();
new Thread(new Service(s)).start();
}
ss.close();
}
}
Service:
public class Service implements Runnable {
private Sockets = null;
public Service(Socket s){
this.s = s;
}
@Override
public void run(){
// TODO Auto-generatedmethod stub
try {
InputStream ips = s.getInputStream();
OutputStream ops = s.getOutputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(ips));
PrintWriter pw = new PrintWriter(ops,true);
while(true){
String strLine = br.readLine();
if(strLine.equalsIgnoreCase("quit")){
break;
}
System.out.println(strLine +":" + strLine.length());
String strEcho = (new StringBuffer(strLine).reverse()).toString();
pw.println(strLine +"-->" + strEcho);
}
br.close();
pw.close();
s.close();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
TCP服务器程序模型的编写要点:
a) TCP服务器程序要想能接收多个客户端连接,需要循环调用ServerSocket.accept()方法。
b) 服务器程序与每个客户端连接的绘画过程不能互相影响,需要在独立的线程中运行。
c) 一个线程服务对象与一个服务器端Socket对象相关联,共同来完成与一个客户端的会话。
15.如何检测和解决端口冲突问题
a)使用netstat命令查看当前正在被使用的TCP端口号。
b)通过一个配置参数来指定TCP服务程序所使用的端口号
c)将用户所指定的端口号保存到一个文件中,当服务器程序下次启动运行时,之间从文件中读取那个端口号