ghfwokao ghfwokao
关注数: 170 粉丝数: 231 发帖数: 11,993 关注贴吧数: 9
Socket用ObjectOutputStream流传输字节数组的问题,附测试代码 客户端 import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; public class Client { private Socket clientSocket; private ObjectOutputStream oos; private ObjectInputStream ois; public Client(String ip,int port) { try { clientSocket=new Socket(ip, port); oos=new ObjectOutputStream(clientSocket.getOutputStream()); ois=new ObjectInputStream(clientSocket.getInputStream()); System.out.println("连接服务器成功"); } catch (UnknownHostException e) { System.out.println("连接服务器失败"); e.printStackTrace(); } catch (IOException e) { System.out.println("连接服务器失败"); e.printStackTrace(); } } public void clientSend(MessageBean ms) { try { oos.writeObject(ms); } catch (IOException e) { System.out.println("客户端发送失败"); e.printStackTrace(); } } public void clientSend(ArrayList<String> list) { try { oos.writeObject(list); } catch (IOException e) { System.out.println("客户端发送失败"); e.printStackTrace(); } } public void clientReceive() { new Thread(new Runnable() { @Override public void run() { try { ois.readObject(); } catch (IOException e) { System.out.println("客户端接收失败"); e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("客户端接收失败"); e.printStackTrace(); } } }).start(); } public static void main(String[] args) { Client cl=new Client(Tool.getLocalIp(), 20000); cl.clientReceive(); ArrayList<String> list=new ArrayList<String>(); list.add("1"); list.add("2"); cl.clientSend(list); byte[] buf=new byte[4]; for(int i=0;i<buf.length;i++) { buf[i]=(byte)i; } MessageBean m=new MessageBean("", 1, null, buf, 0); System.out.println("初始buf[0]="+m.getBuf()[0]); cl.clientSend(m); buf[0]=12; m.setBuf(buf); System.out.println("改变后buf[0]="+m.getBuf()[0]); cl.clientSend(m); } } class Tool { public static String getLocalIp() { InetAddress it=null; try { it=InetAddress.getLocalHost(); } catch (UnknownHostException e) { System.out.println("获取本机IP失败"); e.printStackTrace(); } System.out.println(it.getHostAddress()); return it.getHostAddress(); } }
首页 1 2 下一页