1.获得Socket信息
ServerSocketFrame.java
import java.awt.*;
import javax.swing.*;
import java.net.*;
public class ServerSocketFrame extends JFrame{
private JTextArea ta_info;
private ServerSocket server;
private Socket socket;
public void getserver(){
try{
server=new ServerSocket(1978);
ta_info.append("服务器套接字已经创建成功\n");
while(true){
ta_info.append("等待客户机的连接......\n");
socket=server.accept();//实例化socket对象
ta_info.append("连接成功.....\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
ServerSocketFrame frame=new ServerSocketFrame();
frame.setVisible(true);
frame.getserver();
}
public ServerSocketFrame(){
super();
this.setTitle("服务器端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,336,257);
JScrollPane scrollPane=new JScrollPane();
this.getContentPane().add(scrollPane,BorderLayout.CENTER);
ta_info=new JTextArea();
scrollPane.setViewportView(ta_info);
}
}
ClientSocketFrame.java
import java.awt.*;
import javax.swing.*;
import java.net.*;
public class ClientSocketFrame extends JFrame{
private Socket socket;
private JTextArea ta=new JTextArea();
public static void main(String args[]){
ClientSocketFrame client=new ClientSocketFrame();
client.setVisible(true);
client.connect();
}
public ClientSocketFrame(){
super();
this.setTitle("获取Socket信息");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,351,257);
JScrollPane scrollPane=new JScrollPane();
this.getContentPane().add(scrollPane,BorderLayout.CENTER);
scrollPane.setViewportView(ta);
}
private void connect(){
ta.append("尝试连接.....\n");
try{
socket=new Socket("192.168.16.1",1978);
ta.append("完成连接.....\n");
InetAddress netAddress=socket.getInetAddress();
String netIp=netAddress.getHostAddress();//获得远程服务器的IP地址
int netPort=socket.getPort();//获得远程服务器的端口号
InetAddress localAddress=socket.getLocalAddress();//获得客户端的IP地址
String localIp=localAddress.getHostAddress();//获得客户端的IP地址
int localPort=socket.getLocalPort();//获得客户端的端口号
ta.append("远程服务器的IP地址: "+netIp+"\n");
ta.append("远程服务器的端口号: "+netPort+"\n");
ta.append("客户机本地的IP地址: "+localIp+"\n");
ta.append("客户机本地的端口号: "+localPort+"\n");
}catch(Exception e){
e.printStackTrace();
}
}
}
2.接收和发送Socket信息
服务器端接收来自客户端发送的信息
ServerSocketFrame.java
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class ServerSocketFrame extends JFrame{
private JTextArea ta_info;
private ServerSocket server;
private Socket socket;
private BufferedReader reader;
public static void main(String args[]){
ServerSocketFrame frame=new ServerSocketFrame();
frame.setVisible(true);
frame.getServer();
}
public ServerSocketFrame(){
super();
this.setTitle("服务器端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,336,257);
JScrollPane scrollPane=new JScrollPane();
this.getContentPane().add(scrollPane,BorderLayout.CENTER);
ta_info=new JTextArea();
scrollPane.setViewportView(ta_info);
}
public void getServer(){
try{
server=new ServerSocket(1978);
ta_info.append("服务器套接字已经创建成功\n");
while(true){
ta_info.append("等待客户机的连接.....\n");
socket=server.accept();
ta_info.append("连接成功.....\n");
InputStreamReader in=new InputStreamReader(socket.getInputStream());
reader=new BufferedReader(in);
getClientInfo();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void getClientInfo(){
try{
while(true){
ta_info.append("接收到客户机发送的消息: "+reader.readLine()+"\n");
}
}catch(Exception e){
ta_info.append("客户端已退出....\n");
}finally{
try{
if(reader!=null){
reader.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
ClientSocketFrame.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ClientSocketFrame extends JFrame{
private PrintWriter writer;
private Socket socket;
private JTextArea ta_info=new JTextArea();
private JTextField tf_send=new JTextField();
public static void main(String args[]){
ClientSocketFrame frame=new ClientSocketFrame();
frame.setVisible(true);
frame.connect();
}
public ClientSocketFrame(){
super();
this.setTitle("客户端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,351,257);
this.getContentPane().add(tf_send,"South");
tf_send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
writer.println(tf_send.getText());
ta_info.append("客户端发送的信息是: "+tf_send.getText()+"\n");
tf_send.setText(null);
}
});
JScrollPane scrollPane=new JScrollPane();
this.getContentPane().add(scrollPane,BorderLayout.CENTER);
scrollPane.setViewportView(ta_info);
}
private void connect(){
ta_info.append("尝试连接......\n");
try{
socket=new Socket("192.168.16.1",1978);
writer=new PrintWriter(socket.getOutputStream(),true);
ta_info.append("完成连接..\n");
}catch(Exception e){
e.printStackTrace();
}
}
}
3.使用Socket通信
服务器发送信息 客户端可以接收 客户端发送信息 服务器也可以接收
ServerSocketFrame.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ServerSocketFrame extends JFrame{
private JTextField tf_send;
private JTextArea ta_info;
private ServerSocket server;
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
public static void main(String args[]){
ServerSocketFrame frame=new ServerSocketFrame();
frame.setVisible(true);
frame.getserver();
}
public ServerSocketFrame(){
super();
this.setTitle("服务器端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 379, 260);
JScrollPane scrollpane=new JScrollPane();
this.getContentPane().add(scrollpane,BorderLayout.CENTER);
ta_info=new JTextArea();
scrollpane.setViewportView(ta_info);
JPanel panel=new JPanel();
this.getContentPane().add(panel,BorderLayout.NORTH);
JLabel label=new JLabel();
label.setText("服务器发送的信息: ");
panel.add(label);
tf_send=new JTextField();
tf_send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
writer.println(tf_send.getText());//将文本框信息写入流
ta_info.append("服务器发送的信息是: "+tf_send.getText()+"\n");
tf_send.setText(null);
}
});
tf_send.setPreferredSize(new Dimension(220,25));
panel.add(tf_send);
}
public void getserver(){
try{
server=new ServerSocket(1978);
ta_info.append("服务器套接字已经创建成功\n");
while(true){
ta_info.append("等待客户机的连接.....\n");
socket=server.accept();
InputStreamReader in=new InputStreamReader(socket.getInputStream());
reader=new BufferedReader(in);
writer=new PrintWriter(socket.getOutputStream(),true);
getClientInfo();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void getClientInfo(){
try{
while(true){
String line=reader.readLine();
if(line!=null){
ta_info.append("接收到客户机发送的信息: "+line+"\n");
}
}
}catch(Exception e){
ta_info.append("客户端已退出....\n");
}finally{
try{
if(reader!=null){
reader.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
ClientSocketFrame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import java.io.*;
public class ClientSocketFrame extends JFrame{
private JLabel label;
private JPanel panel;
private JTextArea ta_info=new JTextArea();
private JTextField tf_send=new JTextField();
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
public static void main(String args[]){
ClientSocketFrame frame=new ClientSocketFrame();
frame.setVisible(true);
frame.connect();
}
public ClientSocketFrame(){
super();
this.setTitle("客户端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 361, 257);
JScrollPane scrollpane=new JScrollPane();
getContentPane().add(scrollpane, BorderLayout.CENTER);
scrollpane.setViewportView(ta_info);
this.getContentPane().add(getPanel(),BorderLayout.NORTH);
}
public void connect(){
ta_info.append("尝试连接.....\n");
try{
socket=new Socket("192.168.16.1",1978);
while(true){
writer=new PrintWriter(socket.getOutputStream(),true);
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
ta_info.append("完成连接....\n");
getClientInfo();
}
}catch(Exception e){
e.printStackTrace();
}
}
private void getClientInfo(){
try{
while(true){
if(reader!=null){
String line=reader.readLine();
if(line!=null){
ta_info.append("接收到服务器发送的信息: "+line+"\n");
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(reader!=null){
reader.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
protected JPanel getPanel(){
if(panel==null){
panel=new JPanel();
panel.add(getLabel());
tf_send.setPreferredSize(new Dimension(200,25));
panel.add(tf_send);
tf_send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
writer.println(tf_send.getText());
ta_info.append("客户端发送的信息是: "+tf_send.getText()+"\n");
tf_send.setText(null);
}
});
}
return panel;
}
protected JLabel getLabel(){
if(label==null){
label=new JLabel();
label.setText("客户端发送的信息: ");
}
return label;
}
}
4.使用Socket传递对象
对 对象进行序列化 在服务器和客户端接受信息的时候也与普通的信息有区别
Student.java
import java.io.*;
public class Student implements Serializable{//序列化对象类
private String id;
private String name;
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
ServerSocketFrame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import java.io.*;
public class ServerSocketFrame extends JFrame{
private JTextField tf_name;
private JTextField tf_id;
private JTextArea ta_info;
private ServerSocket server;
private Socket socket;
private ObjectOutputStream out=null;
private ObjectInputStream in=null;
//Java中ObjectInputStream 与 ObjectOutputStream这两个包装类可用于输入流中读取对象类数据和
//将对象类型的数据写入到底层输入流
public static void main(String args[]){
ServerSocketFrame frame=new ServerSocketFrame();
frame.setVisible(true);
frame.getserver();
}
public ServerSocketFrame(){
super();
this.setTitle("服务器端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,399,260);
JScrollPane scrollPane=new JScrollPane();
this.getContentPane().add(scrollPane,BorderLayout.CENTER);
ta_info=new JTextArea();
scrollPane.setViewportView(ta_info);
JPanel panel=new JPanel();
this.getContentPane().add(panel,BorderLayout.NORTH);
JLabel label=new JLabel();
label.setText("编号: ");
panel.add(label);
tf_id=new JTextField();
tf_id.setPreferredSize(new Dimension(100,25));
panel.add(tf_id);
JLabel label_1=new JLabel();
label_1.setText("名称: ");
panel.add(label_1);
tf_name=new JTextField();
tf_name.setPreferredSize(new Dimension(100,25));
panel.add(tf_name);
JButton button=new JButton();
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Student stud=new Student();
stud.setId(tf_id.getText());
stud.setName(tf_name.getText());
try{
out.writeObject(stud);
}catch(IOException e1){
e1.printStackTrace();
}
ta_info.append("服务器发送的编号是: "+tf_id.getText()+" 名称是: "+tf_name.getText()+"\n");
tf_id.setText(null);
tf_name.setText(null);
}
});
button.setText("发 送");
panel.add(button);
}
private void getClientInfo(){
try{
while(true){
Student stud=(Student)in.readObject();
if(stud!=null){
ta_info.append("接收到客户机发送的编号为: "+stud.getId()+" 名称为: "+stud.getName()+"\n");
}
}
}catch(Exception e){
ta_info.append("客户端已经退出.....\n");
}finally{
try{
if(in!=null){
in.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public void getserver(){
try{
server=new ServerSocket(1978);
ta_info.append("服务器套接字已经创建成功....\n");
while(true){
ta_info.append("等待客户机的连接......\n");
socket=server.accept();
ta_info.append("客户机连接成功....\n");
out=new ObjectOutputStream(socket.getOutputStream());
in=new ObjectInputStream(socket.getInputStream());
getClientInfo();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
ClientSocketFrame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import java.io.*;
public class ClientSocketFrame extends JFrame{
private JTextField tf_id=new JTextField();
private JTextField tf_name=new JTextField();
private JTextArea ta_info=new JTextArea();
private Socket socket;
private ObjectInputStream in=null;
private ObjectOutputStream out=null;
private JButton button;
private JLabel label;
private JLabel label_1;
private JPanel panel;
public static void main(String args[]){
ClientSocketFrame frame=new ClientSocketFrame();
frame.setVisible(true);
frame.connect();
}
public ClientSocketFrame(){
super();
this.setTitle("客户端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,393,257);
JScrollPane scrollPane=new JScrollPane();
this.getContentPane().add(scrollPane,BorderLayout.CENTER);
scrollPane.setViewportView(ta_info);
this.getContentPane().add(getPanel(),BorderLayout.NORTH);
}
public void getClientInfo(){
try{
while(true){
Student stud=(Student)in.readObject();
if(stud!=null)
ta_info.append("接收到服务器发送的编号为: "+stud.getId()+" 名称为: "+stud.getName()+"\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(in!=null){
in.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
private void connect(){
ta_info.append("尝试连接.....\n");
try{
socket=new Socket("192.168.16.1",1978);
while(true){
out=new ObjectOutputStream(socket.getOutputStream());
in=new ObjectInputStream(socket.getInputStream());
ta_info.append("完成连接.....\n");
getClientInfo();
}
}catch(Exception e){
e.printStackTrace();
}
}
protected JPanel getPanel(){
if(panel==null){
panel=new JPanel();
panel.add(getLabel());
tf_id.setPreferredSize(new Dimension(100,25));
panel.add(tf_id);
panel.add(getLabel_1());
// tf_name=new JTextField();
tf_name.setPreferredSize(new Dimension(100,25));
panel.add(tf_name);
// panel.add(getTf_name());
button=new JButton();
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Student stud=new Student();
stud.setId(tf_id.getText());
stud.setName(tf_name.getText());
try{
out.writeObject(stud);
}catch(IOException e1){
e1.printStackTrace();
}
ta_info.append("客户端发送的编号是: "+tf_id.getText()+" 名称: "+tf_name.getText()+"\n");
tf_id.setText(null);
tf_name.setText(null);
}
});
button.setText("发 送");
panel.add(button);
}
return panel;
}
protected JLabel getLabel(){
if(label==null){
label=new JLabel();
label.setText("编号: ");
}
return label;
}
protected JLabel getLabel_1(){
if(label_1==null){
label_1=new JLabel();
label_1.setText("名称: ");
}
return label_1;
}
// protected JTextField getTf_name(){
// if(tf_name==null){
// tf_name=new JTextField();
// tf_name.setPreferredSize(new Dimension(100,25));
// }
// return tf_name;
// }
// protected JButton getButton(){
// if(button==null){
// button=new JButton();
// button.addActionListener(new ActionListener(){
//
// @Override
// public void actionPerformed(ActionEvent e) {
// // TODO Auto-generated method stub
// Student stud=new Student();
// stud.setId(tf_id.getText());
// stud.setName(tf_name.getText());
// try{
// out.writeObject(stud);
// }catch(IOException e1){
// e1.printStackTrace();
// }
// ta_info.append("客户端发送的编号是: "+tf_id.getText()+" 名称: "+tf_name.getText()+"\n");
// tf_id.setText(null);
// tf_name.setText(null);
// }
// });
// button.setText("发 送");
// }
// return button;
// }
}
4.使用Socket传输图片
服务器和客户端分别有两个小窗口显示发出的图片和接收的图片
ServerSocketFrame.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.BevelBorder;
import java.net.*;
import java.io.*;
import javax.imageio.*;
public class ServerSocketFrame extends JFrame{
private Image sendImage=null;
private Image receiveImage=null;
private SendImagePanel sendImagePanel=null;
private ReceiveImagePanel receiveImagePanel=null;
private File imageFile=null;//声明所选择图片的File对象
private JTextField tf_path;
private DataOutputStream out=null;
private DataInputStream in=null;
private ServerSocket server;
private Socket socket;
private long lengths=-1;//图片文件的大小
public static void main(String args[]){
ServerSocketFrame frame=new ServerSocketFrame();
frame.setVisible(true);
frame.getServer();
}
public void getServer(){
try{
server=new ServerSocket(1978);
while(true){
socket=server.accept();
out=new DataOutputStream(socket.getOutputStream());
in=new DataInputStream(socket.getInputStream());
getClientInfo();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void getClientInfo(){
try{
long lengths=in.readLong();//读取图片文件的长度
byte[] bt=new byte[(int)lengths];
for(int i=0;i<bt.length;i++){
bt[i]=in.readByte();//读取字节信息并存储到字节数组
}
receiveImage=new ImageIcon(bt).getImage();//创建图像对象
receiveImagePanel.repaint();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(in!=null)
in.close();
if(socket!=null)
socket.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
public ServerSocketFrame(){
super();
this.setTitle("服务器端程序");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 379, 260);
JPanel panel=new JPanel();
this.getContentPane().add(panel,BorderLayout.NORTH);
JLabel label=new JLabel();
label.setText("路径: ");
panel.add(label);
tf_path=new JTextField();
tf_path.setPreferredSize(new Dimension(140,25));
panel.add(tf_path);
sendImagePanel=new SendImagePanel();
receiveImagePanel=new ReceiveImagePanel();
JButton button=new JButton();
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try{
DataInputStream inStream=null;
if(imageFile!=null){
lengths=imageFile.length();
inStream=new DataInputStream(new FileInputStream(imageFile));
//创建输入流对象
}
else{
JOptionPane.showMessageDialog(null, "还没选择图片文件。");
return;
}
out.writeLong(lengths);
byte[] bt=new byte[(int)lengths];
int len=-1;
while((len=inStream.read(bt))!=-1){
out.write(bt);
}
}catch(IOException e1){
e1.printStackTrace();
}
}
});
button.setText("发 送");
panel.add(button);
JButton button_1=new JButton();
button_1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser fileChooser=new JFileChooser();
FileNameExtensionFilter filter=new FileNameExtensionFilter("图像文件(JPG/GIF/BMP",
"JPG","JPEG","GIF","BMP");
fileChooser.setFileFilter(filter);
int flag=fileChooser.showOpenDialog(null);
if(flag==JFileChooser.APPROVE_OPTION){//获得选中的文件对象
imageFile=fileChooser.getSelectedFile();
}
if(imageFile!=null){
tf_path.setText(imageFile.getAbsolutePath());//图片完整路径
try{
sendImage=ImageIO.read(imageFile);
}catch(IOException e1){
e1.printStackTrace();
}
}
sendImagePanel.repaint();
}
});
button_1.setText("选择图片");
panel.add(button_1);
JPanel panel_1=new JPanel();
panel_1.setLayout(new BorderLayout());
this.getContentPane().add(panel_1,BorderLayout.CENTER);
JPanel panel_2=new JPanel();
panel_2.setLayout(new GridLayout(1,0));
FlowLayout flowLayout=new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
panel_2.setLayout(flowLayout);
panel_1.add(panel_2,BorderLayout.NORTH);
JLabel label_1=new JLabel();
label_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
label_1.setText("服务器端选择的要发送的图片 ");
panel_2.add(label_1);
JLabel label_2=new JLabel();
label_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
label_2.setText("接收到客户端发送的图片 ");
panel_2.add(label_2);
JPanel imgPanel=new JPanel();
GridLayout gridLayout=new GridLayout(1,0);
gridLayout.setVgap(10);//设置组件之间垂直间距,就是在这个容器内的俩个控件的上下相隔的距离
imgPanel.setLayout(gridLayout);
panel_1.add(imgPanel,BorderLayout.CENTER);
imgPanel.add(sendImagePanel);
imgPanel.add(receiveImagePanel);
sendImagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
receiveImagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
}
class SendImagePanel extends JPanel{
public void paint(Graphics g){
if(sendImage!=null){
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.drawImage(sendImage,0,0,this.getWidth(), this.getHeight(),this);
}
}
}
class ReceiveImagePanel extends JPanel{
public void paint(Graphics g){
if(receiveImage!=null){
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.drawImage(receiveImage,0,0,this.getWidth(), this.getHeight(),this);
}
}
}
}
ClientSocketFrame.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.net.*;
import java.io.*;
public class ClientSocketFrame extends JFrame{
private Image sendImage=null;
private Image receiveImage=null;
private SendImagePanel sendImagePanel=null;
private ReceiveImagePanel receiveImagePanel=null;
private File imageFile=null;
private JTextField tf_path;
private DataInputStream in=null;
private DataOutputStream out=null;
private Socket socket;
private long lengths=-1;
public static void main(String args[]){
ClientSocketFrame frame=new ClientSocketFrame();
frame.setVisible(true);
frame.connect();
}
public void connect(){
try{
socket=new Socket("192.168.16.1",1978);
while(true){
if(socket!=null&&!socket.isClosed()){
out=new DataOutputStream(socket.getOutputStream());
in=new DataInputStream(socket.getInputStream());
getServerInfo();
}else{
socket=new Socket("192.168.16.1",1978);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void getServerInfo(){
try{
long lengths=in.readLong();//读取图片的长度
byte[] bt=new byte[(int)lengths];
for(int i=0;i<bt.length;i++){
bt[i]=in.readByte();
}
receiveImage=new ImageIcon(bt).getImage();
receiveImagePanel.repaint();
}catch(Exception e){
}finally{
try{
if(in!=null){
in.close();
}
if(socket!=null){
socket.close();
}
}catch(IOException e1){
e1.printStackTrace();
}
}
}
public ClientSocketFrame(){
super();
this.setTitle("客户端程序");
this.setBounds(100,100,373,257);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel();
this.getContentPane().add(panel,BorderLayout.NORTH);
JLabel label=new JLabel();
label.setText("路径: ");
panel.add(label);
tf_path=new JTextField();
tf_path.setPreferredSize(new Dimension(140,25));
panel.add(tf_path);
JButton button=new JButton();
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser fileChooser=new JFileChooser();
FileNameExtensionFilter filter=new FileNameExtensionFilter("图像文件(JPG/GIF/GMP)",
"JPG","JPEG","GIF","BMP");//创建过滤器
fileChooser.setFileFilter(filter);
int flag=fileChooser.showOpenDialog(null);
if(flag==JFileChooser.APPROVE_OPTION){
imageFile=fileChooser.getSelectedFile();
//获取选中的图片对象
}
if(imageFile!=null){
tf_path.setText(imageFile.getAbsolutePath());
try{
sendImage=ImageIO.read(imageFile);
}catch(IOException e1){
e1.printStackTrace();
}
}
sendImagePanel.repaint();
}
});
button.setText("选择图片");
panel.add(button);
JButton button_1=new JButton();
button_1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try{
DataInputStream inStream=null;
if(imageFile!=null){
lengths=imageFile.length();
inStream=new DataInputStream(new FileInputStream(imageFile));
}else{
JOptionPane.showMessageDialog(null, "还没有选择图片文件");
return;
}
out.writeLong(lengths);
byte[] bt=new byte[(int)lengths];
int len=-1;
while((len=inStream.read(bt))!=-1){
out.write(bt);
}
}catch(IOException e1){
e1.printStackTrace();
}
}
});
button_1.setText("发 送");
panel.add(button_1);
JPanel panel_1=new JPanel();
panel_1.setLayout(new BorderLayout());
this.getContentPane().add(panel_1,BorderLayout.CENTER);
JPanel panel_2=new JPanel();
panel_2.setLayout(new GridLayout(1,0));
panel_1.add(panel_2,BorderLayout.NORTH);
JLabel label_1=new JLabel();
label_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
label_1.setText("客户端选择的要发送的图片");
panel_2.add(label_1);
JLabel label_2=new JLabel();
label_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
label_2.setText("接收到服务器发送的图片 ");
panel_2.add(label_2);
JPanel imagePanel=new JPanel();
sendImagePanel=new SendImagePanel();
receiveImagePanel=new ReceiveImagePanel();
imagePanel.add(sendImagePanel);
imagePanel.add(receiveImagePanel);
GridLayout gridLayout=new GridLayout(1,0);
gridLayout.setVgap(6);
imagePanel.setLayout(gridLayout);
panel_1.add(imagePanel,BorderLayout.CENTER);
}
class SendImagePanel extends JPanel{
public void paint(Graphics g){
if(sendImage!=null){
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.drawImage(sendImage, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
}
class ReceiveImagePanel extends JPanel{
public void paint(Graphics g){
if(receiveImage!=null){
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.drawImage(receiveImage, 0, 0, this.getWidth(), this.getHeight(), this);
}
}
}
}
4.使用Socket传递对象