서버측에서 클라이언트로 소켓을 통해 전달된 이미지를 JFrame 윈도우에 출력하는 예
Server.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.kdea.filetransfer;
import java.io.*;
import java.net.*;
/**
*
* @author duniv6-000
*/
public class Server
{
public static void main(String[] args)
{
init();
}
private static void init()
{
ServerSocket ss = null;
try {
while(true) {
ss = new ServerSocket(1234);
System.out.println("서버 대기중....");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
FileInputStream fin = new FileInputStream("d:/test/sample.jpg");
byte[] buf = new byte[1024];
int read = 0;
while((read=fin.read(buf, 0, buf.length))!=-1)
{
os.write(buf, 0, read);
}
fin.close();
os.close();
System.out.println("파일 전송완료");
}
} catch (IOException ex) {
ex.printStackTrace();
//Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Client.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.kdea.filetransfer;
import java.awt.image.BufferedImage;
import java.net.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* @author duniv6-000
*/
public class Client
{
public static void init()
{
Socket socket = null;
try {
socket = new Socket("localhost", 1234);
InputStream is = socket.getInputStream();
BufferedImage bi = ImageIO.read(is);
ImageIcon icon = new ImageIcon(bi);
ClientFrame.mFrame.displayImage(icon);
System.out.println("수신된 이미지를 화면에 출력함");
} catch (Exception ex) {
ex.printStackTrace();
//Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ClientFrame.java
public static ClientFrame mFrame;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
mFrame = new ClientFrame();
mFrame.setVisible(true);
}
});
}
.....
.....
......... 중략
public void displayImage(ImageIcon icon)
{
labelImg.setIcon(icon);
}
// 메뉴 아이템을 클릭하면 실행되는 이벤트 핸들러 메소드
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
Client.init();
}