我是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);
}
}
}