我是java新手,有点卡在我的媒体控制项目上。我需要做的是将图像和文本发送到客户端应用程序。我找到了一些接收图像并显示它的示例代码(下面列出)。这工作得很好,但我需要有一种将图像和文本发送到相同套接字连接的方式。如何在同一个Java套接字上发送图像和文本?
它的存在决定它是什么类型的数据的一种方式?如果它是图像,我希望它可以显示它,如果是文本,则显示msgbox。
我应该有两个插槽,一个用于图像,另一个用于文本?
不幸的是在示例代码中的变量名是不是英语,这使得它有点难以遵循:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Cliente extends JFrame {
JTextField tf;
Lienzo lienzo;
Socket con;
ObjectOutputStream salida;
ObectInputStream entrada;
public Cliente(){
super("Cliente");
Container c = getContentPane();
tf = new JTextField(10);
lienzo = new Lienzo();
c.add(lienzo);
pack();
setSize(100,100);
setVisible(true);
}
void ejecutar(){
try{
con = new Socket("127.0.0.1",5700);
salida = new ObjectOutputStream(con.getOutputStream());
salida.flush();
entrada = new ObjectInputStream(con.getInputStream());
procesar();
}
catch(IOException e){}
}
void procesar() throws IOException {
try{
while(true){
ImageIcon img = (ImageIcon) entrada.readObject();
escribir(img);
}
}catch(ClassNotFoundException e){}
}
void escribir(final ImageIcon img){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
lienzo.pinta(img);
}
}
);
}
public static void main(String args[]){
Cliente cl = new Cliente();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.ejecutar();
}
class Lienzo extends JPanel{
ImageIcon img = null ;
public Lienzo(){
}
public void pinta(ImageIcon img){
this.img = img;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(img!=null)
img.paintIcon(this,g,10,10);
}
}
}