java tcp網路通訊 傳輸檔案

smilestone322發表於2017-08-31

初學java 實現tcp網路通訊 介面使用windowBuilder,介面如下:

首先服務端監聽埠號8005,啟動服務後,等待客戶端連線。


客戶端首先選擇需要傳輸的檔案,然後啟動連線,就開始傳輸檔案了。

服務端的原始碼如下:

package transfServer;
import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.*;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FileTransfServer extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField ipAddress;
	private JTextField Port;
    private Socket socket;  			//accept 後sock
    private String filePath="E:\\testJava"; 
    private boolean bStartFlag=false;
    
	//IP地址
	private String strIp="";
	private int nPort=0;
	
	public void ReadData(Socket sock) {  
        
        try{
            InputStream input = sock.getInputStream(); //開啟 inputStream資源  
            byte[] fileNameByte = new byte[1024];        //存放fileName  
            int fileNameLenth; 							//讀取的字元長度  
              
            fileNameLenth = input.read(fileNameByte);   
            String fileName = new String(fileNameByte,0,fileNameLenth); //還原fileName  
              
            System.out.println(Thread.currentThread().getName() + fileName);  
              
            //下面是接受檔案  
            BufferedOutputStream output  =   
                    new BufferedOutputStream(new FileOutputStream(new File(filePath, fileName)));  
              
            byte[] buff = new byte[1024*1024*5];  
            int len;  
              
            while ( (len = input.read(buff))!=-1){  
                output.write(buff, 0, len);  
            }  
              
            
            System.out.println("receive finished!");  
              
            output.close();  
            sock.close();  
        	
        }catch(Exception e){
        	System.out.println(e);
        	
        }
 
    }  

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			FileTransfServer dialog = new FileTransfServer();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public FileTransfServer() {
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		
		JLabel lblIpAddress = new JLabel("Ip Address:");
		lblIpAddress.setBounds(14, 23, 91, 18);
		contentPanel.add(lblIpAddress);
		{
			JLabel lblPort = new JLabel("Port:");
			lblPort.setBounds(14, 61, 91, 18);
			contentPanel.add(lblPort);
		}
		
		//ip地址
		ipAddress = new JTextField("127.0.0.1");
		ipAddress.setBounds(119, 20, 86, 24);
		contentPanel.add(ipAddress);
		ipAddress.setColumns(10);
		
		//埠號
		Port = new JTextField("8005");
		Port.setColumns(10);
		Port.setBounds(119, 58, 86, 24);
		
		contentPanel.add(Port);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton btnStartServer = new JButton("啟動服務");
				btnStartServer.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						//啟動服務新增的程式碼
						//獲取ip地址和埠號
						strIp=ipAddress.getText();       //伺服器IP,此處沒有用到
						String strPort=Port.getText();
						//String to int
						nPort=Integer.parseInt(strPort);  //伺服器埠號
						
						//啟動服務函式
						try{
							ServerSocket server = new ServerSocket(nPort); 
							bStartFlag=true;
							while(bStartFlag)
							{
								
							   Socket socket = server.accept();  
							   ReadData(socket);
      server.close();
      Thread.sleep(100);
							}
						}catch(Exception e)
						{
							System.out.println(e);
						}
					}
				});
				btnStartServer.setActionCommand("StartServer");
				buttonPane.add(btnStartServer);
				getRootPane().setDefaultButton(btnStartServer);
			}
			{
				JButton cancelButton = new JButton("停止服務");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						//新增取消命令的程式碼
						bStartFlag=false;
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}
}



客戶端的原始碼如下:

package transfClient;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.awt.event.ActionEvent;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.net.*;

public class FileTransfClient extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField IpAddress;
	private JTextField Port;
	private JTextField FileDir;
	private String filePath="";
	private String strIp="";
	private int nPort=0;

	//傳送檔案程式碼
	public void SendFile(String strIp,int nPort) 
	{
		//
		try
		{
			//不處理異常編譯不過
			InetAddress address=InetAddress.getByName(strIp);
			Socket servSock=new Socket(address,nPort);
			File file =   new File (filePath);  
			String fileName = file.getName();  
	        OutputStream out = servSock.getOutputStream();  
	        //傳輸檔名
	        out.write(fileName.getBytes());  
	        
	        BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));  
	          
	        byte[] buff = new byte[1024*1024];  
	        int len;  
	          
	        while (( len=input.read(buff) )!=-1){  
	            out.write(buff,0,len);  
	        }  

	        servSock.close();  
			
		}catch(Exception e)
		{
			System.out.println(e);
		}
	}
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			FileTransfClient dialog = new FileTransfClient();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setTitle("檔案傳輸客戶端");
			dialog.setVisible(true);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public FileTransfClient() {
		setBounds(100, 100, 708, 362);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		{
			JLabel lblNewLabel = new JLabel("Ip Address:");
			lblNewLabel.setBounds(14, 27, 91, 18);
			contentPanel.add(lblNewLabel);
		}
		{
			JLabel lblPort = new JLabel("Port:");
			lblPort.setBounds(14, 69, 91, 18);
			contentPanel.add(lblPort);
		}
		{
			//IP 地址
			IpAddress = new JTextField("127.0.0.1");
			IpAddress.setBounds(119, 24, 86, 24);
			contentPanel.add(IpAddress);
			IpAddress.setColumns(10);
		}
		{
			//埠號
			Port = new JTextField("8005");
			Port.setColumns(10);
			Port.setBounds(119, 66, 86, 24);
			contentPanel.add(Port);
		}
		{
			JLabel label = new JLabel("檔案路徑:");
			label.setBounds(14, 112, 91, 18);
			contentPanel.add(label);
		}
		{
			FileDir = new JTextField("");
			FileDir.setColumns(10);
			FileDir.setBounds(119, 109, 373, 24);
			contentPanel.add(FileDir);
		}
		
		JButton browseBtn = new JButton("瀏覽");
		browseBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//瀏覽Btn訊息相應函式
				JFileChooser jf=new JFileChooser();
				jf.setDialogTitle("請選擇需要傳送的檔案");
				FileNameExtensionFilter filter=new FileNameExtensionFilter("文字檔案(*.txt;*.kcd)","txt","kcd");
				jf.setFileFilter(filter);
				int returnVal=jf.showOpenDialog(null);
				if(returnVal ==JFileChooser.APPROVE_OPTION)
				{
					filePath=jf.getSelectedFile().getPath();
					FileDir.setText(filePath);
					
				}
			}
		});
		browseBtn.setActionCommand("Browse");
		browseBtn.setBounds(506, 108, 63, 27);
		contentPanel.add(browseBtn);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton StartConnectBtn = new JButton("啟動連線");
				StartConnectBtn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						//連線伺服器所需程式碼
						//獲取ip地址和埠號
						strIp=IpAddress.getText();       //伺服器IP
						String strPort=Port.getText();
						//String to int
						nPort=Integer.parseInt(strPort);  //伺服器埠號
						
						//傳輸檔案
						SendFile(strIp,nPort);
						
						
					}
				});
				StartConnectBtn.setActionCommand("StartConnect");
				buttonPane.add(StartConnectBtn);
				getRootPane().setDefaultButton(StartConnectBtn);
			}
			{
				JButton SendBtn = new JButton("傳送");
				SendBtn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						//往伺服器傳送檔案所需程式碼
						
					}
				});
				SendBtn.setActionCommand("Send");
				buttonPane.add(SendBtn);
			}
		}
	}
	

}



相關文章