Passing primitives through sockets
I've just started with Java networking, and I have a few questions. Say I've sent a packet, and I know that the first two bytes in that packet combine to make an int. Is this the best way of sending and recieving the data, or is there an easier way?
Client:
publicclass ClientPrim{
Socket socket;
BufferedOutputStream out;
public ClientPrim(){
try{
socket =new Socket("localhost", 9090);
out =new BufferedOutputStream(socket.getOutputStream());
int anInt = 30000;
int anotherInt = 60000;
byte[] bytes =newbyte[4];
bytes[0] = (byte) (anInt>>8);
bytes[1] = (byte) (anInt&0xff);
bytes[2] = (byte) (anotherInt>>8);
bytes[3] = (byte) (anotherInt&0xff);
out.write(bytes, 0, bytes.length);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
publicstaticvoid main(String [] args){
ClientPrim c =new ClientPrim();
}
}
Server:
publicclass ServPrim{
private ServerSocket server;
public ServPrim(){
try{
server =new ServerSocket(9090);
while (true){
Socket con = server.accept();
BufferedInputStream in =new BufferedInputStream(con.getInputStream());
byte[] bytes =newbyte[4];
in.read(bytes, 0, bytes.length);
int firstBig = bytes[0]>=0?bytes[0]:bytes[0]+256;
int firstSmall = bytes[1]>=0?bytes[1]:bytes[1]+256;
int secondBig = bytes[2]>=0?bytes[2]:bytes[2]+256;
int secondSmall = bytes[3]>=0?bytes[3]:bytes[3]+256;
int firstInt = (firstBig<<8) + firstSmall;
int secondInt = (secondBig<<8) + secondSmall;
System.out.println(firstInt+" "+secondInt);
con.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
publicstaticvoid main(String[] args){
ServPrim s =new ServPrim();
}
}
With all the bit operations it seems very messy, surely theres an easier way? I've also managed to send the data via serialized wrapper classes, but will this have a large effect on the speed? I'd rather put in a bit of extra effort and have a fast program
Thanks

