socket, nio socket,及xml传递object 方法

1:如何通过socket代理来访问服务端:

  1. StringproxyHost="192.168.204.212";
  2. StringproxyPort="1080";
  3. //通知Java要通过代理进行连接。
  4. System.getProperties().put("socksProxySet","true");
  5. //指定代理所在的机器
  6. System.getProperties().put("socksProxyHost",proxyHost);
  7. //指定代理监听的端口。
  8. System.getProperties().put("socksProxyPort",proxyPort);
  9. Stringhost="134.01.69.80";
  10. intport=12086;
  11. System.out.println("connetioning:"+host+":"+port);
  12. server=newSocket(host,port);

二:老socket传递Object对象:

要传递的对象:

  1. publicclassEmployeeimplementsSerializable{
  2. privateintemployeeNumber;
  3. privateStringemployeeName;
  4. Employee(intnum,Stringname){
  5. employeeNumber=num;
  6. employeeName=name;
  7. }
  8. publicintgetEmployeeNumber(){
  9. returnemployeeNumber;
  10. }
  11. publicvoidsetEmployeeNumber(intnum){
  12. employeeNumber=num;
  13. }
  14. publicStringgetEmployeeName(){
  15. returnemployeeName;
  16. }
  17. publicvoidsetEmployeeName(Stringname){
  18. employeeName=name;
  19. }
  20. }

client:

  1. publicclassClient{
  2. publicstaticvoidmain(String[]arg){
  3. try{
  4. Employeejoe=newEmployee(150,"Joe");
  5. System.out.println("employeeNumber="+joe.getEmployeeNumber());
  6. System.out.println("employeeName="+joe.getEmployeeName());
  7. SocketsocketConnection=newSocket("127.0.0.1",11111);
  8. ObjectOutputStreamclientOutputStream=newObjectOutputStream(
  9. socketConnection.getOutputStream());
  10. ObjectInputStreamclientInputStream=newObjectInputStream(
  11. socketConnection.getInputStream());
  12. clientOutputStream.writeObject(joe);
  13. joe=(Employee)clientInputStream.readObject();
  14. System.out.println("employeeNumber="+joe.getEmployeeNumber());
  15. System.out.println("employeeName="+joe.getEmployeeName());
  16. clientOutputStream.close();
  17. clientInputStream.close();
  18. }catch(Exceptione){
  19. System.out.println(e);
  20. }
  21. }
  22. }

server端:

java 代码
  1. publicclassServer{
  2. publicstaticvoidmain(String[]arg){
  3. Employeeemployee=null;
  4. try{
  5. ServerSocketsocketConnection=newServerSocket(11111);
  6. System.out.println("ServerWaiting");
  7. Socketpipe=socketConnection.accept();
  8. ObjectInputStreamserverInputStream=newObjectInputStream(pipe
  9. .getInputStream());
  10. ObjectOutputStreamserverOutputStream=newObjectOutputStream(pipe
  11. .getOutputStream());
  12. employee=(Employee)serverInputStream.readObject();
  13. employee.setEmployeeNumber(256);
  14. employee.setEmployeeName("li");
  15. serverOutputStream.writeObject(employee);
  16. serverInputStream.close();
  17. serverOutputStream.close();
  18. }catch(Exceptione){
  19. System.out.println(e);
  20. }
  21. }
  22. }

三:nio socket传递Object:

client:

  1. publicclassClient{
  2. privateStringhostname;
  3. privateintport;
  4. publicClient(Stringhostname,intport)
  5. {
  6. this.hostname=hostname;
  7. this.port=port;
  8. }
  9. publicstaticvoidmain(String[]args){
  10. Stringhostname="192.168.0.81";
  11. intport=8234;
  12. Studentstu=newStudent();
  13. stu.setId(849);
  14. stu.setName("Squall");
  15. Clientclient=newClient(hostname,port);
  16. try{
  17. client.write(stu);
  18. }catch(IOExceptione){
  19. //TODOAuto-generatedcatchblock
  20. e.printStackTrace();
  21. }
  22. }
  23. publicvoidwrite(Objectobj)throwsIOException{
  24. SocketChannelchannel=null;
  25. try{
  26. channel=SocketChannel.open(newInetSocketAddress(hostname,port));
  27. ByteBufferbuf=Client.getByteBuffer(obj);
  28. channel.write(Client.getByteBuffer(obj));
  29. channel.write(Client.getByteBuffer(obj));
  30. }catch(Exceptione){
  31. e.printStackTrace();
  32. }finally{
  33. channel.close();
  34. }
  35. }
  36. publicstaticByteBuffergetByteBuffer(Objectobj)throwsIOException
  37. {
  38. ByteArrayOutputStreambOut=newByteArrayOutputStream();
  39. ObjectOutputStreamout=newObjectOutputStream(bOut);
  40. out.writeObject(obj);
  41. out.flush();
  42. byte[]arr=bOut.toByteArray();
  43. System.out.println("Objectin"+arr.length+"bytes");
  44. ByteBufferbb=ByteBuffer.wrap(arr);
  45. out.close();
  46. returnbb;
  47. }
  48. }

server端:

java 代码
  1. publicclassServer{
  2. publicstaticvoidmain(String[]args){
  3. System.out.println("inserver!");
  4. ServerThreadserver=newServerThread();
  5. newThread(server).start();
  6. }
  7. staticclassServerThreadimplementsRunnable{
  8. publicvoidrun(){
  9. try{
  10. ServerSocketChannelsc=ServerSocketChannel.open();
  11. ServerSockets=sc.socket();
  12. s.bind(newInetSocketAddress(8234));
  13. while(true){
  14. Socketincoming=s.accept();
  15. Runnabler=newGetObjThread(incoming);
  16. Threadt=newThread(r);
  17. t.start();
  18. }
  19. }catch(Exceptione){
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. staticclassGetObjThreadimplementsRunnable{
  25. publicGetObjThread(Sockets){
  26. incoming=s;
  27. }
  28. publicvoidrun(){
  29. try{
  30. SocketChannelsc=incoming.getChannel();
  31. ByteBufferbbIn=ByteBuffer.allocate(1024);
  32. sc.read(bbIn);
  33. sc.close();
  34. bbIn.flip();
  35. ByteArrayInputStreambIn=newByteArrayInputStream(bbIn
  36. .array());
  37. ObjectInputStreamin=newObjectInputStream(bIn);
  38. StudentnStu=(Student)in.readObject();
  39. System.out.println("studentidis"+nStu.getId()+"/n"
  40. +"studentnameis"+nStu.getName());
  41. }catch(IOExceptione){
  42. e.printStackTrace();
  43. }catch(ClassNotFoundExceptione){
  44. e.printStackTrace();
  45. }
  46. }
  47. privateSocketincoming;
  48. }
  49. }

四:备份一个有用的util class:对象序列化,反序列化(序列化对象转byte[],ByteBuffer, byte[]转object: 

java 代码
  1. publicclassByteUtil{
  2. publicstaticbyte[]getBytes(Objectobj)throwsIOException
  3. {
  4. ByteArrayOutputStreambout=newByteArrayOutputStream();
  5. ObjectOutputStreamout=newObjectOutputStream(bout);
  6. out.writeObject(obj);
  7. out.flush();
  8. byte[]bytes=bout.toByteArray();
  9. bout.close();
  10. out.close();
  11. returnbytes;
  12. }
  13. publicstaticObjectgetObject(byte[]bytes)throwsIOException,ClassNotFoundException
  14. {
  15. ByteArrayInputStreambi=newByteArrayInputStream(bytes);
  16. ObjectInputStreamoi=newObjectInputStream(bi);
  17. Objectobj=oi.readObject();
  18. bi.close();
  19. oi.close();
  20. returnobj;
  21. }
  22. publicstaticByteBuffergetByteBuffer(Objectobj)throwsIOException
  23. {
  24. byte[]bytes=ByteUtil.getBytes(obj);
  25. ByteBufferbuff=ByteBuffer.wrap(bytes);
  26. returnbuff;
  27. }
  28. }

五:如何通过xml传递Object对象:

可以先把object转成一个byte[]数组,然后用base64编码成一个base64格式的String,放入xml的CDATA中,就可以传了。

接收方,收到该xml后,把CDATA中的String用base64解码为byte[],进而根据四中的方法,还原为object:

java 代码
  1. publicclassBase64{
  2. publicstaticStringgetEncodedText(byte[]bytes){
  3. try{
  4. BASE64Encoderencoder=newBASE64Encoder();
  5. Stringtext=encoder.encode(bytes);
  6. returntext;
  7. }catch(Exceptione){
  8. e.printStackTrace();
  9. returnnull;
  10. }
  11. }
  12. publicstaticbyte[]decode(Stringsrc)
  13. {
  14. BASE64Decoderdecoder=newBASE64Decoder();
  15. try{
  16. returndecoder.decodeBuffer(src);
  17. }catch(IOExceptione){
  18. //TODOAuto-generatedcatchblock
  19. e.printStackTrace();
  20. returnnull;
  21. }
  22. }
  23. publicstaticvoidmain(String[]args){
  24. Strings="ly89";
  25. byte[]bytes=s.getBytes();
  26. Stringencode=Base64.getEncodedText(bytes);
  27. System.out.println("theencodestringis:"+encode);
  28. byte[]dbytes=Base64.decode(encode);
  29. for(inti=0;i<bytes.length;i++){
  30. System.out.println(dbytes[i]);
  31. }
  32. }
  33. }

你可能感兴趣的:(socket)