版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
第Java聊天室之使用Socket實現(xiàn)傳遞圖片目錄一、題目描述二、解題思路三、代碼詳解
一、題目描述
題目實現(xiàn):使用網(wǎng)絡(luò)編程時,需要通過Socket傳遞圖片。
二、解題思路
創(chuàng)建一個服務(wù)器類:ServerSocketFrame,繼承JFrame類
寫一個getserver()方法,實例化Socket對象,啟用9527當(dāng)服務(wù)的端口。
創(chuàng)建輸入流對象,用來接收客戶端信息。
再定義一個getClientInfo()方法,用于接收客戶端發(fā)送的信息。
對文本框添加一個事件:實現(xiàn)向客戶端發(fā)磅信息。
創(chuàng)建一個客戶端類:ClientSocketFrame,繼承JFrame類。
寫一個connect()方法,實例化Socket對象,連接本地服務(wù)的9527端口服務(wù)。
再定義一個getClientInfo()方法,用于接收服務(wù)端發(fā)送的信息。
技術(shù)重點:
通過使用DataInputStream類的read0方法,將圖片文件讀取到字節(jié)數(shù)組,然后使用DataOutputStream類從DataOutput類繼承的write0方法輸出字節(jié)數(shù)組,從而實現(xiàn)了使用Socket傳輸圖片的功能。
三、代碼詳解
ServerSocketFrame
packagecom.xiaoxuzhu;
importjava.awt.BorderLayout;
importjava.awt.Dimension;
importjava.awt.FlowLayout;
importjava.awt.Graphics;
importjava.awt.GridLayout;
importjava.awt.Image;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.*;
import.*;
importjavax.imageio.ImageIO;
importjavax.swing.ImageIcon;
importjavax.swing.JButton;
importjavax.swing.JFileChooser;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.border.BevelBorder;
importjavax.swing.border.EtchedBorder;
importjavax.swing.filechooser.FileFilter;
importjavax.swing.filechooser.FileNameExtensionFilter;
*Description:
*@authorxiaoxuzhu
*@version1.0
*pre
*修改記錄:
*修改后版本修改人修改日期修改內(nèi)容
*2025/6/4.1xiaoxuzhu2025/6/4Create
*/pre
*@date2025/6/4
publicclassServerSocketFrameextendsJFrame{
privateImagesendImg=null;//聲明圖像對象
privateImagereceiveImg=null;//聲明圖像對象
privateSendImagePanelsendImagePanel=null;//聲明圖像面板對象
privateReceiveImagePanelreceiveImagePanel=null;//聲明圖像面板對象
privateFileimgFile=null;//聲明所選擇圖片的File對象
privateJTextFieldtf_path;
privateDataOutputStreamout=null;//創(chuàng)建流對象
privateDataInputStreamin=null;//創(chuàng)建流對象
privateServerSocketserver;//聲明ServerSocket對象
privateSocketsocket;//聲明Socket對象socket
privatelonglengths=-1;//圖片文件的大小
publicvoidgetServer(){
try{
server=newServerSocket(9527);//實例化Socket對象
while(true){//如果套接字是連接狀態(tài)
socket=server.accept();//實例化Socket對象
out=newDataOutputStream(socket.getOutputStream());//獲得輸出流對象
in=newDataInputStream(socket.getInputStream());//獲得輸入流對象
getClientInfo();//調(diào)用getClientInfo()方法
}catch(Exceptione){
e.printStackTrace();//輸出異常信息
privatevoidgetClientInfo(){
try{
longlengths=in.readLong();//讀取圖片文件的長度
byte[]bt=newbyte[(int)lengths];//創(chuàng)建字節(jié)數(shù)組
for(inti=0;ibt.length;i++){
bt[i]=in.readByte();//讀取字節(jié)信息并存儲到字節(jié)數(shù)組
receiveImg=newImageIcon(bt).getImage();//創(chuàng)建圖像對象
receiveImagePanel.repaint();//重新繪制圖像
}catch(Exceptione){
}finally{
try{
if(in!=null){
in.close();//關(guān)閉流
if(socket!=null){
socket.close();//關(guān)閉套接字
}catch(IOExceptione){
e.printStackTrace();
publicstaticvoidmain(String[]args){//主方法
ServerSocketFrameframe=newServerSocketFrame();//創(chuàng)建本類對象
frame.setVisible(true);
frame.getServer();//調(diào)用方法
publicServerSocketFrame(){
super();
setTitle("服務(wù)器端程序");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,379,260);
finalJPanelpanel=newJPanel();
getContentPane().add(panel,BorderLayout.NORTH);
finalJLabellabel=newJLabel();
label.setText("路徑:");
panel.add(label);
tf_path=newJTextField();
tf_path.setPreferredSize(newDimension(140,25));
panel.add(tf_path);
sendImagePanel=newSendImagePanel();
receiveImagePanel=newReceiveImagePanel();
finalJButtonbutton_1=newJButton();
button_1.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
JFileChooserfileChooser=newJFileChooser();//創(chuàng)建文件選擇器
FileFilterfilter=newFileNameExtensionFilter(
"圖像文件(JPG/GIF/BMP)","JPG","JPEG","GIF","BMP");//創(chuàng)建過濾器
fileChooser.setFileFilter(filter);//設(shè)置過濾器
intflag=fileChooser.showOpenDialog(null);//顯示打開對話框
if(flag==JFileChooser.APPROVE_OPTION){
imgFile=fileChooser.getSelectedFile();//獲取選中圖片的File對象
if(imgFile!=null){
tf_path.setText(imgFile.getAbsolutePath());//圖片完整路徑
try{
sendImg=ImageIO.read(imgFile);//構(gòu)造BufferedImage對象
}catch(IOExceptionex){
ex.printStackTrace();
sendImagePanel.repaint();//調(diào)用paint()方法
button_1.setText("選擇圖片");
panel.add(button_1);
finalJButtonbutton=newJButton();
button.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
try{
DataInputStreaminStream=null;//定義數(shù)據(jù)輸入流對象
if(imgFile!=null){
lengths=imgFile.length();//獲得選擇圖片的大小
inStream=newDataInputStream(newFileInputStream(imgFile));//創(chuàng)建輸入流對象
}else{
JOptionPane.showMessageDialog(null,"還沒有選擇圖片文件。");
return;
out.writeLong(lengths);//將文件的大小寫入輸出流
byte[]bt=newbyte[(int)lengths];//創(chuàng)建字節(jié)數(shù)組
intlen=-1;
while((len=inStream.read(bt))!=-1){//將圖片文件讀取到字節(jié)數(shù)組
out.write(bt);//將字節(jié)數(shù)組寫入輸出流
}catch(IOExceptione1){
e1.printStackTrace();
button.setText("發(fā)送");
panel.add(button);
finalJPanelpanel_1=newJPanel();
panel_1.setLayout(newBorderLayout());
getContentPane().add(panel_1,BorderLayout.CENTER);
finalJPanelpanel_2=newJPanel();
panel_2.setLayout(newGridLayout(1,0));
finalFlowLayoutflowLayout=newFlowLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
panel_2.setLayout(flowLayout);
panel_1.add(panel_2,BorderLayout.NORTH);
finalJLabellabel_1=newJLabel();
label_1.setBorder(newEtchedBorder(EtchedBorder.LOWERED));
label_1.setText("服務(wù)器端選擇的要發(fā)送的圖片");
panel_2.add(label_1);
finalJLabellabel_2=newJLabel();
label_2.setBorder(newEtchedBorder(EtchedBorder.LOWERED));
label_2.setText("接收到客戶端發(fā)送的圖片");
panel_2.add(label_2);
finalJPanelimgPanel=newJPanel();
finalGridLayoutgridLayout=newGridLayout(1,0);
gridLayout.setVgap(10);
imgPanel.setLayout(gridLayout);
panel_1.add(imgPanel,BorderLayout.CENTER);
imgPanel.add(sendImagePanel);
imgPanel.add(receiveImagePanel);
sendImagePanel.setBorder(newBevelBorder(BevelBorder.LOWERED));
receiveImagePanel.setBorder(newBevelBorder(BevelBorder.LOWERED));
//創(chuàng)建面板類
classSendImagePanelextendsJPanel{
publicvoidpaint(Graphicsg){
if(sendImg!=null){
g.clearRect(0,0,this.getWidth(),this.getHeight());//清除繪圖上下文的內(nèi)容
g.drawImage(sendImg,0,0,this.getWidth(),this.getHeight(),
this);//繪制指定大小的圖片
//創(chuàng)建面板類
classReceiveImagePanelextendsJPanel{
publicvoidpaint(Graphicsg){
if(receiveImg!=null){
g.clearRect(0,0,this.getWidth(),this.getHeight());//清除繪圖上下文的內(nèi)容
g.drawImage(receiveImg,0,0,this.getWidth(),
this.getHeight(),this);//繪制指定大小的圖片
}
ClientSocketFrame
packagecom.xiaoxuzhu;
importjava.awt.BorderLayout;
importjava.awt.Container;
importjava.awt.Dimension;
importjava.awt.Graphics;
importjava.awt.GridLayout;
importjava.awt.Image;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
import.Socket;
importjavax.imageio.ImageIO;
importjavax.swing.JButton;
importjavax.swing.ImageIcon;
importjavax.swing.JFileChooser;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.border.EtchedBorder;
importjavax.swing.filechooser.FileFilter;
importjavax.swing.filechooser.FileNameExtensionFilter;
*Description:
*@authorxiaoxuzhu
*@version1.0
*pre
*修改記錄:
*修改后版本修改人修改日期修改內(nèi)容
*2025/6/4.1xiaoxuzhu2025/6/4Create
*/pre
*@date2025/6/4
publicclassClientSocketFrameextendsJFrame{
privateImagesendImg=null;//聲明圖像對象
privateImagereceiveImg=null;//聲明圖像對象
privateSendImagePanelsendImagePanel=null;//聲明圖像面板對象
privateReceiveImagePanelreceiveImagePanel=null;//聲明圖像面板對象
privateFileimgFile=null;//聲明所選擇圖片的File對象
privateJTextFieldtf_path;
privateDataInputStreamin=null;//創(chuàng)建流對象
privateDataOutputStreamout=null;//創(chuàng)建流對象
privateSocketsocket;//聲明Socket對象
privateContainercc;//聲明Container對象
privatelonglengths=-1;//圖片文件的大小
privatevoidconnect(){//連接套接字方法
try{//捕捉異常
socket=newSocket("",9527);//實例化Socket對象
while(true){
if(socket!=null!socket.isClosed()){
out=newDataOutputStream(socket.getOutputStream());//獲得輸出流對象
in=newDataInputStream(socket.getInputStream());//獲得輸入流對象
getServerInfo();//調(diào)用getServerInfo()方法
}else{
socket=newSocket("",9527);//實例化Socket對象
}catch(Exceptione){
e.printStackTrace();//輸出異常信息
publicstaticvoidmain(String[]args){//主方法
ClientSocketFrameclien=newClientSocketFrame();//創(chuàng)建本例對象
clien.setVisible(true);//將窗體顯示
clien.connect();//調(diào)用連接方法
privatevoidgetServerInfo(){
try{
longlengths=in.readLong();//讀取圖片文件的長度
byte[]bt=newbyte[(int)lengths];//創(chuàng)建字節(jié)數(shù)組
for(inti=0;ibt.length;i++){
bt[i]=in.readByte();//讀取字節(jié)信息并存儲到字節(jié)數(shù)組
receiveImg=newImageIcon(bt).getImage();//創(chuàng)建圖像對象
receiveImagePanel.repaint();//重新繪制圖像
}catch(Exceptione){
}finally{
try{
if(in!=null){
in.close();//關(guān)閉流
if(socket!=null){
socket.close();//關(guān)閉套接字
}catch(IOExceptione){
e.printStackTrace();
*Createtheframe
publicClientSocketFrame(){
super();
setTitle("客戶端程序");
setBounds(100,100,373,257);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
finalJPanelpanel=newJPanel();
getContentPane().add(panel,BorderLayout.NORTH);
finalJLabellabel=newJLabel();
label.setText("路徑:");
panel.add(label);
tf_path=newJTextField();
tf_path.setPreferredSize(newDimension(140,25));
panel.add(tf_path);
finalJButtonbutton=newJButton();
button.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
JFileChooserfileChooser=newJFileChooser();//創(chuàng)建文件選擇器
FileFilterfilter=newFileNameExtensionFilter(
"圖像文件(JPG/GIF/BMP)","JPG","JPEG","GIF","BMP");//創(chuàng)建過濾器
fileChooser.setFileFilter(filter);//設(shè)置過濾器
intflag=fileChooser.showOpenDialog(null);//顯示打開對話框
if(flag==JFileChooser.APPROVE_OPTION){
imgFile=fileChooser.getSelectedFile();//獲取選中圖片的File對象
if(imgFile!=null){
tf_path.setText(imgFile.getAbsolutePath());//圖片完整路徑
try{
sendImg=ImageIO.read(imgFile);//構(gòu)造BufferedImage對象
}catch(IOExceptionex){
ex.printStackTrace();
sendImagePanel.repaint();//調(diào)用paint()方法
button.setText("選擇圖片");
panel.add(button);
finalJButtonbutton_1=newJButton();
button_1.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
try{
DataInputStreaminStream=null;//定義數(shù)據(jù)輸入流對象
if(imgFile!=null){
lengths=imgFile.length();//獲得選擇圖片的大小
inStream=newDataInputStream(newFileInputStream(
imgFile));//創(chuàng)建輸入流對象
}else{
JOptionPane.showMessageDialog(null,"還沒有選擇圖片文件。");
return;
out.writeLong(lengths);//將文件的大小寫入輸出流
byte[]bt=newbyte[(int)lengths];//創(chuàng)建字節(jié)數(shù)組
intlen=-1;
while((len=inStream.read(bt))!=-1){//將圖片文件讀取到字節(jié)數(shù)組
out.write(bt);//將字節(jié)數(shù)組寫入輸出流
}catch(IOExceptione1){
e1.printStackTrace();
button_1.setText("發(fā)送");
panel.add(button_1);
finalJPanelpanel_1=newJPanel();
panel_1.setLayout(newBorderLayout());
getContentPane().add(panel_1,BorderLayout.CENTER);
finalJPanelpanel_2=newJPanel();
panel_2.setLayout(newGridLayout(1,0));
panel_1.add(panel_2,BorderLayout.NORTH);
fi
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2026年河南工業(yè)和信息化職業(yè)學(xué)院單招綜合素質(zhì)筆試備考試題含詳細(xì)答案解析
- 2026年通化醫(yī)藥健康職業(yè)學(xué)院單招綜合素質(zhì)考試模擬試題含詳細(xì)答案解析
- 2026年江西傳媒職業(yè)學(xué)院單招綜合素質(zhì)筆試備考題庫含詳細(xì)答案解析
- 2025河北承德市寬城滿族自治縣人力資源和社會保障局招聘公益性崗位人員11人參考考試試題及答案解析
- 2026年南昌理工學(xué)院單招綜合素質(zhì)考試備考題庫含詳細(xì)答案解析
- 2026年中山職業(yè)技術(shù)學(xué)院單招職業(yè)技能考試參考題庫含詳細(xì)答案解析
- 2026年寧德職業(yè)技術(shù)學(xué)院單招綜合素質(zhì)考試備考試題含詳細(xì)答案解析
- 2026年景德鎮(zhèn)藝術(shù)職業(yè)大學(xué)單招綜合素質(zhì)考試模擬試題含詳細(xì)答案解析
- 2026年麗江師范高等??茖W(xué)校單招綜合素質(zhì)筆試備考試題含詳細(xì)答案解析
- 2026年安陽幼兒師范高等??茖W(xué)校單招綜合素質(zhì)考試參考題庫含詳細(xì)答案解析
- 肉雞采食量影響因素分析與調(diào)控研究進(jìn)展
- T-CCTAS 237-2025 城市軌道交通市域快線車輛運營技術(shù)規(guī)范
- 軟件系統(tǒng)上線測試與驗收報告
- 冬季交通安全測試題及答案解析
- 2025年國家能源局系統(tǒng)公務(wù)員面試模擬題及備考指南
- (2025年標(biāo)準(zhǔn))圈內(nèi)認(rèn)主協(xié)議書
- 2025年安徽省中考化學(xué)真題及答案
- 2025年軍隊文職人員統(tǒng)一招聘面試( 臨床醫(yī)學(xué))題庫附答案
- 海馬體核磁掃描課件
- 某電力股份企業(yè)同熱三期2×100萬千瓦項目環(huán)評報告書
- 2026屆上海市部分區(qū)中考一模語文試題含解析
評論
0/150
提交評論