1. 程式人生 > >Java 網絡編程 之 TCP協議

Java 網絡編程 之 TCP協議

art 表示 true 主機名 margin tput and net 寫入

TCP協議 (服務器端程先啟動,等待客戶端連接)

TCP協議是面向連接的通信協議,即在傳輸數據前先在發送端和接收端建立邏輯連接,然後再傳輸數據

保證傳輸數據的全性安,文件數據不易丟失

JDK中提供了兩個類用於實現TCP程序,一個是ServerSocket類,用於表示服務器端,一個是Socket類,用於表示客戶端。

首先創建代表服務器端的ServerSocket對象,並等待客戶端的連接,

然後創建代表客戶端的Socket對象向服務器端發出連接請求,服務器端響應請求,客戶端再次向服務器端發送確認信息,確認連接

public class TCPClient {//客戶端

public static void main(String[] args) throws IOException {

Socket socket=new Socket("127.0.0.1",8888);//客戶端對象 建連接

//Socket socket=new Socket(inet,8888);//(地址對象,端口號)

OutputStream out=socket.getOutputStream();//客戶端的 輸出流

//寫數據

Scanner sc=new Scanner(System.in);

String str=sc.nextLine();

out.write(str.getBytes());

//明確數據源

FileInputStream fis=new FileInputStream("F:\\java\\1.jpg");

//BufferedInputStream bis = new BufferedInputStream(fis);

//寫數據

int len=0;

byte[] bytes=new byte[1024];

while((len=fis.read(bytes))!=-1){ //bis.read(bytes)

out.write(bytes,0,len); //寫入 socket的 輸出流

}

socket.shutdownOutput();//socket對象 的輸出流 寫入結束符

//接收服務器端的響應

InputStream in=socket.getInputStream();

byte[] bytes=new byte[1024];

int len=in.read(bytes);

System.out.println(new String(bytes,0,len));

socket.close();//釋放內存

fis.close();//關閉數據源

}

}

int port=socket.getPort();//獲取端口號

InetAddress inet=getLocalAddress();//獲取本地地址對象

public class TCPServer {//服務器端

public static void main(String[] args) throws IOException {

ServerSocket server=new ServerSocket(8888);//服務端對象(端口號)

Socket socket=server.accept();//創建連接 獲取客戶端對象

InputStream in=socket.getInputStream();//客戶端的 輸入 不關

//讀出數據

byte[] bytes=new byte[1024];

int len=in.read(bytes);

System.out.println(new String(bytes,0,len));

//明確目的地

File file=new File("F:\\aaa");

if(!file.exists()){ file.mkdirs(); }//文件夾不存在 創建

String fn="oracle"+System.currentTimeMillis()//域名+毫秒值

          +new Random().nextInt(999999)+".jpg";//+六位隨機數+後綴

FileOutputStream fos=new FileOutputStream(file+File.separator+fn);

//BufferedOutputStream bos = new BufferedOutputStream(fos);

//開始復制

byte[] bytes=new byte[1024];

int len=0;

while((len=in.read(bytes))!=-1){

fos.write(bytes,0,len); //bos.write(bytes,0,len);

}

//發送給客戶端響應

OutputStream out=socket.getOutputStream();//輸出流

Scanner sc=new Scanner(System.in);

String str=sc.nextLine();

out.write(str.getBytes());//寫數據

out.write("上傳成功".getBytes());//寫數據

server.close();//釋放資源

fos.close(); //bos.close();

}

}

InetAddress address = socket.getInetAddress();//獲取地址對象

String ip=address.getHostAddress(); //ip地址

String name=address.getHostName(); //主機名

System.out.println("來自IP:"+ip+"主機名:"+name);

多線程(多人同時訪問服務器)
public class Upload implements Runnable{
    private Socket socket;
    public Upload(){}
    public Upload(Socket socket){this.socket=socket;}
    public void run() {
        FileOutputStream fos=null;
        try{
        InputStream in=socket.getInputStream();//客戶端 輸入流
        //明確目的地
        File file=new File("F:\\aaa");
        if(!file.exists()){ file.mkdirs(); }//文件夾不存在  創建
        String filename="oracle"+System.currentTimeMillis()//域名+毫秒值
                    +new Random().nextInt(999999)+".jpg";//+六位隨機數+後綴
        fos=new FileOutputStream(file+File.separator+filename);
        //開始復制
        byte[] bytes=new byte[1024];
        int len=0;
        while((len=in.read(bytes))!=-1){fos.write(bytes,0,len);}
        //發送給客戶端響應
        OutputStream out=socket.getOutputStream();//輸出流
        out.write("上傳成功".getBytes());//寫數據
        }catch(IOException ex){ex.printStackTrace();}
     finally{ if(fos!=null){fos.close();//點try...catch} }
    }
}       

public class TCPThreadServer {//服務器端 多線程  (客戶端不變)
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(8888);//服務端對象(端口號)
        while(true){
            Socket socket=server.accept();//創建連接  獲取客戶端對象 
new Thread(new Upload(socket)).start();
//創建並開啟線程 } } }

Java 網絡編程 之 TCP協議