網絡編程
網絡模型
OSI參考模型
TCP/IP參考模型

學的網絡編程主要在應用層(我想android、JavaWeb、QQ、夢幻西遊等吧,估計是)、傳輸層和網際層混,每個層都有自己的協議規則。
傳輸層主要用TCP(同步;麵向連接,數據量大)、UDP(異步;麵向無連接,大小限製在64k內,QQ聊天、網絡視頻用的UDP)
網際層主要用IP協議
應用層協議:HTTP
網絡通訊要素
IP地址:標識網絡上的電腦的,相當於給電腦取個唯一的名字 192.168.1.1,最大隻能設置255這是字節的最大數,(8個1的二進製轉10進製得出的)
127.0.0.1本地回環地址。IP地址數據太多也難記,所以取了名字127.0.0.1 = localhost
IP/v6不IP/v4的組合數更大,IP/6還包含字符
端口號‘:用來標識電腦上的網絡應用程序的,(為什麼A同學,通過QQ用網絡發個信息給B同學,然後B同學隻能用QQ接受,而不能用飛秋或其他程序接收呢?或者A同學的QQ怎麼準確的發給了B同學的QQ上了呢?這就是端口體現的作用了。)
0-1024端口,一般留給係統用,有0-65535個端口
傳輸協議:通訊的規則。(就像A同學用英文,而B同學用中文,他們兩能交流嗎?)所以網絡上的2台電腦要通信就要用同一個規則。
國際組織定義了通用的協議是TCP/IP協議,也是我們最常用的。它能用於廣域網也能用於局域網。也還有其他的協議。特有的組織或單位有自己特有的通信協議。
Socket
使用最頻繁的三個方法:connect、getInputStream、getOutputStream
通信的兩端都有Socket、網絡通信其實就是Socket間的通信、數據在2個Socket之間通過IO流傳輸。
套接字,使應用程序能夠讀寫與收發通訊協定(protocol)與資料的程序 。(邏輯上的插座)

操作流程(玩Socket主要玩的就是這個流程)
建立發送端,接收端
建立數據包
調用Socket的發送接收方法
關閉Socket。
發送端與接收端是兩個獨立的運行程序。(類比於服務端和客戶端)
Socket的UDP傳輸協議
DatagramSocket與DatagramPacket
DatagramSocket幫助文檔的解說(即發送又接收,客戶端服務端都得有)
此類表示用來發送和接收數據報包的套接字。
數據報套接字是包投遞服務的發送或接收點。每個在數據報套接字上發送或接收的包都是單獨編址和路由的。從一台機器發送到另一台機器的多個包可能選擇不同的路由,也可能按不同的順序到達。
在 DatagramSocket 上總是啟用 UDP 廣播發送。為了接收廣播包,應該將 DatagramSocket 綁定到通配符地址。在某些實現中,將 DatagramSocket 綁定到一個更加具體的地址時廣播包也可以被接收。
示例:DatagramSocket s = new DatagramSocket(null);
s.bind(new InetSocketAddress(8888));
這等價於:DatagramSocket s = new DatagramSocket(8888); 兩個例子都能創建能夠在 UDP 8888 端口上接收廣播的 DatagramSocket。
DatagramPacket(把數據封裝成包,接收和封裝數據)
此類表示數據報包。
數據報包用來實現無連接包投遞服務。每條報文僅根據該包中包含的信息從一台機器路由到另一台機器。從一台機器發送到另一台機器的多個包可能選擇不同的路由,也可能按不同的順序到達。不對包投遞做出保證。
示例代碼:
import java.io.*;
import java.net.*;
/**
* UDP協議的網絡聊天程序(服務器端)
*
* @author Terry
* @date 2014-6-15
*
*/
public class UdpSend {
public static void main(String[] args) throws Exception{
byte[] buf = "我是服務端".getBytes();//創建發送器
DatagramSocket ds = new DatagramSocket();//創建要發送的包
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.101"),10000);
ds.send(dp);
ds.close();
}
}
class UdpRece{
public static void main(String[] args) throws Exception{
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+"--"+data+"--"+port);
ds.close();
}
}多次接收客戶端發來的信息
import java.io.*;
import java.net.*;
/**
* UDP協議的網絡聊天程序(服務器端)
*
* @author Terry
* @date 2014-6-15
*
*/
public class UdpSend {
public static void main(String[] args) throws Exception{
DatagramSocket ds = new DatagramSocket();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = null;
while((temp = br.readLine())!=null){
if(temp.equals("886")){
break;
}
DatagramPacket dp =
new DatagramPacket(temp.getBytes(),temp.getBytes().length,InetAddress.getByName("192.168.1.101"),10000);//目的地址,往地址為192.168.1.101的10000端口發送
ds.send(dp);
}
ds.close();
}
}
class UdpRece{
public static void main(String[] args) throws Exception{
DatagramSocket ds = new DatagramSocket(10000);//接收本主機地址的10000端口的包
//DatagramSocket ds = new DatagramSocket();
//ds.connect(InetAddress.getByName("192.168.1.101"),10000);//用這樣的方法連接不行。。。這應該是用來連接服務器的
while(true){
byte[] buf = new byte[1024*64];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);//接收
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+"--"+data+"--"+port);
}
//ds.close();//服務器不要關閉連接
}
}
192.168.1.255(最後的255表示這個域裏麵的廣播地址,發給這個地址的信息,在域裏麵的人都能收到)
模擬聊天程序(出現綁定異常)
import java.io.*;
import java.net.*;
class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
while(true){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip + "--" + data);
}
}catch(Exception e){
throw new RuntimeException("");
}
}
}
public class Rece implements Runnable{
private DatagramSocket ds;
public Rece(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = bufr.readLine())!=null){
if("886".equals(line)){
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002);
ds.send(dp);
}
}catch(Exception e){
throw new RuntimeException("");
}
}
}
class ChatPprogram{
public static void main(String[] args) throws Exception{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
Socket(客戶端)和ServerSocket(服務端)
簡單連接示例代碼:
import java.io.*;
import java.net.*;
class SocketClientTest{
public static void main(String[] a) throws Exception{
System.out.println("222");
Socket s = new Socket("192.168.1.100",20000);
OutputStream out = s.getOutputStream();
out.write("woshikehuduan".getBytes());
s.close();
}
}
class SocketServiceTest{
public static void main(String[] a) throws Exception{
System.out.println("111");
ServerSocket ss = new ServerSocket(20000);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "......connected");
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
s.close();
ss.close();
}
}
客戶端發送信息給服務器並接收服務器發回來的信息,服務器接收客戶端發送的信息並回複信息給客戶端
import java.io.*;
import java.net.*;
class SocketClientTest{
public static void main(String[] a) throws Exception{
System.out.println("222");
Socket s = new Socket("192.168.1.100",20000);
OutputStream out = s.getOutputStream();
out.write("laizhikehuduandewenhou:nihao".getBytes());
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
s.close();
}
}
class SocketServiceTest{
public static void main(String[] a) throws Exception{
System.out.println("111");
ServerSocket ss = new ServerSocket(20000);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "......connected");
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
OutputStream out = s.getOutputStream();
out.write("shoudaobinghuifu:niyehao".getBytes());
s.close();
ss.close();
}
}
小練習,客戶端發送文本給服務端,服務端把收到的文本轉成大寫後再發給客戶端
import java.io.*;
import java.net.*;
class SocketClientTest{
public static void main(String[] a) throws Exception{
//創建Socket並與服務端連接
Socket s = new Socket("192.168.1.100",30000);
//獲得用戶輸入的源的字符流
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
//目的流,要將數據發給誰s.getOutputStream()
//BufferedWriter bufOut =
//new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
//讀取流,要從誰那讀數據
BufferedReader bufIn =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line = bufr.readLine())!=null){
if("over".equals(line)){
break;
}
//bufOut.write(line);//這裏的方法,內部原理是,它不是直接將數據,寫到目的地,而是先//寫到內存中,所以服務器那邊,連接上了,但是沒有收到數據。要//flush(刷新內存),flush會將內存的數據寫入預期目//標
// bufOut.newLine();//這裏加這個方法的原因是?如果不加這個方法,當我把數據發給服務器//,但是服務器在讀的時候,沒有發現回車符號,就會一直在那等。//加這個方法的原因是告訴服務器那邊,什麼時候回車
//好讓服務器讀一行。
//bufOut.flush();//這時候服務器就收到數據了
pw.println(line);
String str = bufIn.readLine();
System.out.println("server:"+str);
}
bufr.close();
s.close();//這裏關閉了後,在服務器的BufferedReader 就會讀到-1.
}
}
class SocketServiceTest{
public static void main(String[] a) throws Exception{
ServerSocket ss = new ServerSocket(30000);
while(true){//為了讓服務器可以處理多人的請求,應該不行,這裏要用線程做吧
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println("ip:"+ip+"....connected");
//從誰那讀數據
BufferedReader bufIn = new BufferedReader(
new InputStreamReader(s.getInputStream()));
//把數據寫給誰
//BufferedWriter bufOut = new BufferedWriter(
//new OutputStreamWriter(s.getOutputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line = bufIn.readLine())!=null){
//bufOut.write(line.toUpperCase());
//bufOut.newLine();//這裏加這個方法的原因是?如果不加這個方法,當我把數據發給客服端
//,但是客戶端在讀的時候,沒有發現回車符號,就會一直在那等。加這個方法的原因是告訴客服端那邊,什麼時候回車
//好讓客戶端讀一行。
//bufOut.flush();
pw.println(line.toUpperCase());
}
s.close();
}
//ss.close();
}
}
網絡版的上傳文件
import java.io.*;
import java.net.*;
class UploadFileClient{
public static void main(String[] a) throws Exception{
Socket s = new Socket("192.168.1.100",10010);//連接服務器
//客戶端找自己機子上的文件
BufferedReader bufr = new BufferedReader(new FileReader("F:\\test\
\SocketTest.java"));
//把Socket的OutputStream包裝一下,這裏是裝飾者設計模式
PrintWriter out = new PrintWriter(s.getOutputStream(),true);//true代表
自動flush
String line = null;
while((line = bufr.readLine())!=null){//讀文件
out.println(line);//寫文件
}
//out.println("over");//不加這個結束標識的話,都在等待著讀的情況發生,
但是用over也不好,萬一文件裏麵有一行就寫的是over呢?
s.shutdownOutput();//禁用Socket的輸出流,類似於打標記
//把Socket的InputStream包裝一下,這裏是裝飾者設計模式
BufferedReader bufIn = new BufferedReader(new InputStreamReader
(s.getInputStream()));
String str = bufIn.readLine();//不寫over這裏會一直等待讀
System.out.println(str);
bufr.close();
s.close();
}
}
class UploadFileServer{
public static void main(String[] a) throws Exception{
ServerSocket ss = new ServerSocket(10010);//綁定端口
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println("ip:"+ip+"....connected");
//Socket的流
BufferedReader bufIn = new BufferedReader(new InputStreamReader
(s.getInputStream()));
//服務器本地的流
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\JSON\
\Desktop\\UploadFileServer.java"));
String line = null;
while((line = bufIn.readLine())!=null){//不寫over這裏會一直等著讀
//if("over".equals(line)){
//break;
//}
out.println(line);
}
//out.flush();
//Socket的流
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
pw.println("上傳成功!");
out.close();
s.close();
}
}
單人上傳圖片
import java.io.*;
import java.net.*;
class PicClient{
public static void main(String[] a)throws Exception{
Socket s = new Socket("192.168.1.100",10007);
FileInputStream fis = new FileInputStream("F:\\java\\圖片<a target=_blank href="file://\\dmhyrz-9420648415.jpg">\\dmhyrz-9420648415.jpg</a>");
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufIn = new byte[1024];
int num = in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
class PicServer{
public static void main(String[] a) throws Exception{
ServerSocket ss = new ServerSocket(10007);
Socket s = ss.accept();
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\JSON\\Desktop\\shangchuan.jpg");
byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
OutputStream out = s.getOutputStream();
out.write("上傳成功".getBytes());
fos.close();
s.close();
ss.close();
}
}接收多人上傳圖片或其他文件的服務器import java.io.*;
import java.net.*;
class PicClient{
public static void main(String[] a)throws Exception{
Socket s = new Socket("192.168.1.100",10007);
FileInputStream fis = new FileInputStream("F:\\java\\圖片\\dmhyrz-9420648415.jpg");
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufIn = new byte[1024];
int num = in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
class PicServer{
public static void main(String[] a) throws Exception{
final ServerSocket ss = new ServerSocket(10007);
new Thread(new Runnable(){
@Override
public void run(){
try{
while(true){
Socket s = ss.accept();
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\JSON\\Desktop\
\"+System.currentTimeMillis()+".jpg");
byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
OutputStream out = s.getOutputStream();
out.write("上傳成功".getBytes());
fos.close();
s.close();
}
//ss.close();
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
}
URL類(get方法)
URLConnection |
openConnection()返回一個 URLConnection 對象,它表示到 URL 所引用的遠程對象的連接。 |
相關知識點:
遇見的問題:
一、在學的過程中遇見過這樣一個問題,在F:盤下有一個Test.java文件
package lie14_1;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(11);
}
}
當在cmd下運行javac Test.java的時候,運行用過,但是用java Test的時候報錯,最後發現是包的問題package lie14_1;把包刪除就可以了。具體原因不詳。
最後更新:2017-04-03 07:57:00