java 服务器和客户端之间利用ObjectInputStream ObjectOutputStream成对传输各种类型的数据


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class Fwq {
    static String s1="fwq1";
    static  String s2="fwq2";
    public static void main(String[] args) throws IOException {
        ServerSocket ss1=new ServerSocket(6000);
        ServerSocket ss2=new ServerSocket(6001);
        Dk1 t1=new Dk1(ss1);
        Dk2 t2=new Dk2(ss2);
        t1.start();
        t2.start();
    }
}
class Dk1 extends Thread{

    ServerSocket ss;
    Dk1(ServerSocket ss){
        this.ss=ss;
    }
    public void run(){
       while (true){
          while(true) {
             Socket sc = null;
             try {
               boolean isrun = true;
               System.out.println(8);

               sc = ss.accept();
               while (isrun == true) {


                   OutputStream os = sc.getOutputStream();
                   ObjectOutputStream objectOutputStream=new ObjectOutputStream(os);
                   String sfwq="fwq1:hello client1";
                   objectOutputStream.writeInt(sfwq.length());
                   objectOutputStream.flush();

                   objectOutputStream.write(sfwq.getBytes(StandardCharsets.UTF_8));
                   objectOutputStream.flush();
//------------------------------------------------------------------------------------------------------
                   InputStream is=sc.getInputStream();
                   ObjectInputStream objectInputStream=new ObjectInputStream(is);
//=================================================================================================
                   char c=objectInputStream.readChar();
                   System.out.println(c);

                   String  s10=objectInputStream.readUTF();
                   System.out.println(s10);

                   int t10=objectInputStream.readInt();
                   System.out.println(t10);

                   System.out.println(objectInputStream.readBoolean());

                   System.out.println(objectInputStream.read());

                   int t11=objectInputStream.readInt();
                   byte[] b11=new byte[t11];
                   objectInputStream.readFully(b11);
                   System.out.println(new String(b11));
//===========================================================================================
                   int byteLength=objectInputStream.readInt();
                   byte[] b=new byte[byteLength];

                   objectInputStream.readFully(b);
                   String s=new String(b);
                   System.out.println(s);


//-----------------------------------------------------------------------------------------------------

               }
               sc.close();

           } catch (IOException e) {
               // throw new RuntimeException(e);
               try {
                   sc.close();
               } catch (IOException ex) {
                   throw new RuntimeException(ex);
               }

               break;
           }
          }
      }
    }
}

class Dk2 extends Thread{

    ServerSocket ss;
    Dk2(ServerSocket ss){
        this.ss=ss;
    }
    public void run(){
        while (true){
            while(true) {

                Socket sc = null;
                try {
                    boolean isrun = true;
                    System.out.println(8.1);
                    sc = ss.accept();
                    while (isrun == true) {

                        OutputStream os = sc.getOutputStream();
                        ObjectOutputStream objectOutputStream=new ObjectOutputStream(os);
                        String sfwq="fwq2:hello client2";
                        objectOutputStream.writeInt(sfwq.length());
                        objectOutputStream.flush();

                        objectOutputStream.write(sfwq.getBytes(StandardCharsets.UTF_8));
                        objectOutputStream.flush();
//------------------------------------------------------------------------------------------------------
                        InputStream is=sc.getInputStream();
                        ObjectInputStream objectInputStream=new ObjectInputStream(is);



                        int byteLength=objectInputStream.readInt();
                        byte[] b=new byte[byteLength];

                        objectInputStream.readFully(b);
                        String s=new String(b);
                        System.out.println(s);


//-----------------------------------------------------------------------------------------------------

                    }
                        sc.close();


                } catch (IOException e) {
                    // throw new RuntimeException(e);
                    try {
                        sc.close();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }

                    break;
                }
            }
        }
    }
}
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client3000 {
    static String jpin="hello";
    static boolean isrun=true;
    public static void main(String[] args) throws IOException, InterruptedException {
       Jp jp=new Jp();
       jp.start();

        Socket sc=new Socket("192.168.43.61",6000);
        while (isrun==true) {
            InputStream is = sc.getInputStream();
            ObjectInputStream objectInputStream=new ObjectInputStream(is);
            int byteLength=objectInputStream.readInt();
            byte[] b=new byte[byteLength];

            objectInputStream.readFully(b);
            String s=new String(b);
            System.out.println(s);

            OutputStream os = sc.getOutputStream();
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(os);
//================================================================================================
            objectOutputStream.writeChar('~');    // 一个字符
            objectOutputStream.flush();

            objectOutputStream.writeUTF("你好");   //一个字符串
            objectOutputStream.flush();

            objectOutputStream.writeInt(123456);   //一个32字节的整数
            objectOutputStream.flush();

            objectOutputStream.writeBoolean(true);  //一个布尔数
            objectOutputStream.flush();

            objectOutputStream.write(2);     //写一个字节的数据
            objectOutputStream.flush();

            byte[] b11={48,49,50};                     //写一byte数组
            objectOutputStream.writeInt(b11.length);
            objectOutputStream.flush();
            objectOutputStream.write(b11,0,b11.length);
            objectOutputStream.flush();

//===============================================================================================

            if(jpin.equals("~")){
                sc.close();
            }
            objectOutputStream.writeInt(jpin.length());
            objectOutputStream.flush();

            objectOutputStream.write(jpin.getBytes(StandardCharsets.UTF_8));
            objectOutputStream.flush();
           Thread.sleep(1000);
        }
        sc.close();
    }
}
class Jp extends  Thread{
    public synchronized void run(){
        while(true) {
            Scanner scanner = new Scanner(System.in);
            Client3000.jpin = scanner.nextLine();

        }
    }
}

 

在socket长连接中流 read() 非常重要,如果选取read方法不当,上面的服务器程序break就退不回accept()状态.

经验证,很多莫名的错误都是流的读取方法不对造成的。

 

为了解决这个流读取的问题,折腾了一两个星期,终于在一本书中发现了用object的读和写的类方法.

其他的read方法在socket长连接中都会发生问题.

还有 服务器和客户端 objectinputstram   objectoutputstream  是配对出现的.不能单方使用.

 

fwq:

​




import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Fwq {
    static String s1="fwq1";
    static  String s2="fwq2";
    static  boolean isin1=true;
    static  boolean isin2=true;
    static  boolean iszx1;
    static  boolean iszx2;
    static  boolean iscopy1;
    static  boolean iscopy2;
    static  byte[] file1;
    static  byte[]  file2;
    static  String filename1;
    static  String filename2;

    static  int  filelength1;
    static  int filelength2;
    public static void main(String[] args) throws IOException {
        ServerSocket ss1=new ServerSocket(6000);
        ServerSocket ss2=new ServerSocket(6001);
        Dk1 t1=new Dk1(ss1);
        Dk2 t2=new Dk2(ss2);
        t1.start();
        t2.start();
    }
}
class Dk1 extends Thread{

    ServerSocket ss;
    Dk1(ServerSocket ss){
        this.ss=ss;
    }
    public void run(){
        while (true){

            while(true) {
                Socket sc = null;
                try {
                    boolean isrun = true;
                    System.out.println(8);
                    Fwq.iszx1=false;
                    sc = ss.accept();
                    Fwq.iszx1=true;
//------------提示连接上服务器-----------------------------------------------------------------
                    OutputStream os1 = sc.getOutputStream();
                    ObjectOutputStream objectOutputStream1= new ObjectOutputStream(os1);
                    objectOutputStream1.writeUTF("已连接服务器1");
                    objectOutputStream1.flush();
//-----------判断对方客户端是否在线-------------------------------------------------------------
                    if(Fwq.iszx2==true){
                        objectOutputStream1.writeBoolean(true);
                        objectOutputStream1.flush();
                    }else {
                        objectOutputStream1.writeBoolean(false);
                        objectOutputStream1.flush();

                        while (Fwq.iszx2==false) {
                            Thread.sleep(1000);
                            objectOutputStream1.writeBoolean(Fwq.iszx2);
                            objectOutputStream1.flush();
                        }
                    }
 //---------判断id-----------------------------------------------------------------------
                    objectOutputStream1.writeUTF("请输入id:");
                    objectOutputStream1.flush();
                    InputStream isid=sc.getInputStream();
                    ObjectInputStream objectInputStreamid=new ObjectInputStream(isid);
                    if(!objectInputStreamid.readUTF().equals("6000")){
                        objectOutputStream1.writeUTF("id错误");
                        objectOutputStream1.flush();
                        sc.close();
                    }else{
                        objectOutputStream1.writeUTF("id正确");
                        objectOutputStream1.flush();
                    }

//---------------------------------------------------------------------------------------------------
                    while (Fwq.iszx1==true) {

                        OutputStream os = sc.getOutputStream();
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
                        objectOutputStream.writeBoolean(Fwq.iszx2);
                        objectOutputStream.flush();
//-----------发送服务器2的聊天信息-----------------------------------------------------------
                        if(Fwq.isin2==true) {
                            objectOutputStream.writeChar('^');
                            objectOutputStream.flush();
                            objectOutputStream.writeUTF(Fwq.s2);
                            objectOutputStream.flush();
                            Fwq.isin2=false;
//-----------发送服务器2上传 文件---------------------------------------------------------
                        }else if(Fwq.iscopy2==true) {
                            objectOutputStream.writeChar('&');
                            objectOutputStream.flush();

                            objectOutputStream.writeUTF(Fwq.filename2);
                            objectOutputStream.writeInt(Fwq.filelength2);
                            objectOutputStream.flush();
                            objectOutputStream.write(Fwq.file2);
                            objectOutputStream.flush();

                            Fwq.iscopy2=false;
                        }else{
                            objectOutputStream.writeChar('*');
                            objectOutputStream.flush();
                        }

//-----------接收客户端1的聊天信息---------------------------------------------------------------------------
                        InputStream is = sc.getInputStream();
                        ObjectInputStream objectInputStream = new ObjectInputStream(is);
                        char pd=objectInputStream.readChar();

                        if(pd=='^') {
                            String s = objectInputStream.readUTF();
                            Fwq.s1 = s;
                            Fwq.isin1 = true;
                            pd='*';
                        }

//--------------接收客户端1上传文件---------------------------------------------------------------------------

                        if(pd=='&'){
                            Fwq.filename1=objectInputStream.readUTF();
                            Fwq.filelength1=objectInputStream.readInt();
                            Fwq.file1=new byte[Fwq.filelength1];
                            objectInputStream.readFully(Fwq.file1);
                            Fwq.iscopy1=true;
                            pd='*';
                        }

//-----------------------------------------------------------------------------------------------------

                    }
                    sc.close();

                } catch (IOException e) {
                    // throw new RuntimeException(e);
                    try {
                        sc.close();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }

                    break;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
//=====================================================================================================
class Dk2 extends Thread{

    ServerSocket ss;
    Dk2(ServerSocket ss){
        this.ss=ss;
    }
    public void run(){
        while (true){

            while(true) {
                Socket sc = null;
                try {
                    boolean isrun = true;
                    System.out.println(8.2);
                    Fwq.iszx2=false;
                    sc = ss.accept();
                    Fwq.iszx2=true;

                    OutputStream os1 = sc.getOutputStream();
                    ObjectOutputStream objectOutputStream1= new ObjectOutputStream(os1);
                    objectOutputStream1.writeUTF("已连接服务器2");
                    objectOutputStream1.flush();

                    if(Fwq.iszx1==true){

                        objectOutputStream1.writeBoolean(true);
                        objectOutputStream1.flush();
                    }else {
                        objectOutputStream1.writeBoolean(false);
                        objectOutputStream1.flush();

                        while (Fwq.iszx1==false) {
                            Thread.sleep(1000);

                            objectOutputStream1.writeBoolean(Fwq.iszx1);
                            objectOutputStream1.flush();
                        }
                    }
 //---------判断id------------------------------------------------------------------------------
                    objectOutputStream1.writeUTF("请输入id:");
                    objectOutputStream1.flush();
                    InputStream isid=sc.getInputStream();
                    ObjectInputStream objectInputStreamid=new ObjectInputStream(isid);
                    if(!objectInputStreamid.readUTF().equals("6000")){
                        objectOutputStream1.writeUTF("id错误");
                        objectOutputStream1.flush();
                        sc.close();
                    }else{
                        objectOutputStream1.writeUTF("id正确");
                        objectOutputStream1.flush();
                    }
//---------------------------------------------------------------------------------------------------
                    while (Fwq.iszx2==true) {


                        OutputStream os = sc.getOutputStream();
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
                        objectOutputStream.writeBoolean(Fwq.iszx1);
                        objectOutputStream.flush();
//-----------发送服务器1的聊天信息-----------------------------------------------------------
                        if(Fwq.isin1==true) {
                            objectOutputStream.writeChar('^');
                            objectOutputStream.flush();
                            objectOutputStream.writeUTF(Fwq.s1);
                            objectOutputStream.flush();
                            Fwq.isin1=false;
//-----------发送服务器1上传 文件---------------------------------------------------------
                        }else if(Fwq.iscopy1==true) {
                            objectOutputStream.writeChar('&');
                            objectOutputStream.flush();

                            objectOutputStream.writeUTF(Fwq.filename1);
                            objectOutputStream.writeInt(Fwq.filelength1);
                            objectOutputStream.flush();
                            objectOutputStream.write(Fwq.file1);
                            objectOutputStream.flush();

                            Fwq.iscopy1=false;
                        }else{
                            objectOutputStream.writeChar('*');
                            objectOutputStream.flush();
                        }

//-----------接收客户端2的聊天信息---------------------------------------------------------------------------
                        InputStream is = sc.getInputStream();
                        ObjectInputStream objectInputStream = new ObjectInputStream(is);
                        char pd=objectInputStream.readChar();


                        if(pd=='^') {
                            String s = objectInputStream.readUTF();
                            Fwq.s2 = s;
                            Fwq.isin2 = true;
                            pd='*';
                        }

//--------------接收客户端2上传文件---------------------------------------------------------------------------

                        if(pd=='&'){
                            Fwq.filename2=objectInputStream.readUTF();
                            Fwq.filelength2=objectInputStream.readInt();
                            Fwq.file2=new byte[Fwq.filelength2];
                            objectInputStream.readFully(Fwq.file2);
                            Fwq.iscopy2=true;
                            pd='*';
                        }

//-----------------------------------------------------------------------------------------------------

                    }
                    sc.close();

                } catch (IOException e) {
                    // throw new RuntimeException(e);
                    try {
                        sc.close();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }

                    break;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

[点击并拖拽以移动]
​

3001:

 

//=====================================================================



import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client3000 {
    static String jpin="hello";
    static boolean isjp=true;
    static boolean isrun=true;
    static  boolean iszx;
    static  String pathfile="";
    static  boolean iscp;
    static String jspath="/Users/wangzhong/1/";
    //-------------------------------------------------------------------------------------------
    // nas 功能: 列出目录全部文件   上传文件  删除文件
    public static String[] dir(String in){
        File file=new File(in);
        String[] out=file.list();
        return  out;
    }





    public static void main(String[] args) {

        try {

            Socket sc = new Socket("192.168.1.14", 6000);
            InputStream is1 = sc.getInputStream();
            //------------接收服务器提示登录信息--------------------------------------------------
            ObjectInputStream objectInputStream1 = new ObjectInputStream(is1);
            System.out.println(objectInputStream1.readUTF());
//----------判断对方服务器是否在线---------------------------------------------------
            boolean isrun=true;
            boolean iszx = objectInputStream1.readBoolean();
            if (iszx== true) {

                System.out.println("对方客户端在线");
            } else {
                System.out.println("对方客户端不在线");
                while (iszx==false){
                    Thread.sleep(1000);
                    iszx=objectInputStream1.readBoolean();
                }
            }
            //-------输入id验证id---------------------------------------------------------------
            System.out.println(objectInputStream1.readUTF());
            OutputStream outputStreamid=sc.getOutputStream();
            ObjectOutputStream objectOutputStreamid=new ObjectOutputStream(outputStreamid);

            Scanner scanner=new Scanner((System.in));
            objectOutputStreamid.writeUTF(scanner.nextLine());
            objectOutputStreamid.flush();
            System.out.println(objectInputStream1.readUTF());

            Jp jp=new Jp();
            jp.start();
//-------------------------------------------------------------------------------------
            while (iszx==true) {

                InputStream is = sc.getInputStream();
                ObjectInputStream objectInputStream = new ObjectInputStream(is);
                boolean isdf=objectInputStream.readBoolean();
                if(isdf==false){
                    System.out.println("对方客户端离线,等待对方连线");
                    Thread.sleep(3000);

                }
                char c = objectInputStream.readChar();
//-----------接收聊天信息---------------------------------------------------------------------
                if (c == '^') {
                    String s = objectInputStream.readUTF();
                    if(s.equals("&")){
                        System.out.println("文件传输开始");
                    }else {
                        System.out.println("客户端1收到:" + s);
                        if(s.equals("dir")){
                       //     String dirpath="/Users/wangzhong/nas/";
                            String[] dirfile=dir(jspath);
                            String  stringout="";
                            for(String x:dirfile){
                                stringout=stringout+x+"    ";
                            }
                            jpin="\n"+stringout+"\n"+jspath;
                            isjp=true;
                            isdf=true;
                        }
                        if(s.length()>4) {
                            String zxml = s.substring(0, 4);

                            if (zxml.equals(("send"))) {
                                pathfile = s.substring(5);
                                pathfile=jspath+pathfile;
                                iscp = true;
                            }
                        }
                    }
                    c='*';
                }

//------------接收对方客户端上传来的文件--------------------------------------------------------

                if(c=='&'){                //上传文件标志符
                    String jsfilename=objectInputStream.readUTF();
                    int jsfilelength=objectInputStream.readInt();
                    byte[] jsfile=new byte[jsfilelength];
                    objectInputStream.readFully(jsfile);

                    FileOutputStream fileOutputStream=new FileOutputStream(Client3000.jspath+jsfilename);
                    fileOutputStream.write(jsfile);
                    fileOutputStream.close();
                    System.out.println(jsfilename+"接收完成");
                    c='*';
                }

                OutputStream os = sc.getOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
//-----------关闭程序---------------------------------------------------------------------
                if ((isjp == true)&&(isdf==true)) {
                    if (jpin.equals("~")) {
                        sc.close();
                        break;
                    }
                    //        if(!jpin.equals("&")) {
//---------发送聊天信息---------------------------------------------------------------------
                    objectOutputStream.writeChar('^');
                    objectOutputStream.flush();
                    objectOutputStream.writeUTF(jpin);
                    objectOutputStream.flush();
                    System.out.println("客户端1发送:" + jpin);
                    isjp = false;
                    iscp = false;
                    //          }
//-----------发送上传文件------------------------------------------------------------------
                }
                else if(iscp==true){
                    objectOutputStream.writeChar('&');    //发送上传文件标志符
                    objectOutputStream.flush();
                    try {
                        File file = new File(Client3000.pathfile);
                        String filename = file.getName();
                        int filelength = (int) file.length();
                        objectOutputStream.writeUTF(filename);
                        objectOutputStream.writeInt(filelength);
                        objectOutputStream.flush();

                        byte[] fsfile = new byte[filelength];
                        FileInputStream fileInputStream = new FileInputStream(file);
                        fileInputStream.read(fsfile);

                        objectOutputStream.write(fsfile);
                        objectOutputStream.flush();
                        System.out.println(filename + "发送完成");
                        iscp = false;
                        isjp = false;
                    }catch (FileNotFoundException e){
                        System.out.println("复制文件路径错误");
                        break;
                    }

                }else{
//----------发送防阻塞符------------------------------------------------------------------
                    objectOutputStream.writeChar('*');
                    objectOutputStream.flush();

                }
                Thread.sleep(200);
            }
            sc.close();
            System.out.println("客户端与服务器连接中断,重新连接");

        }catch (IOException | InterruptedException e){
            System.out.println("连接中断.重新启动程序");
            //    throw new RuntimeException(e);
        }
    }
}

//============键盘输入类==========================================================
class Jp extends  Thread{
    public synchronized void run(){
        while(true) {
            Scanner scanner = new Scanner(System.in);
            Client3000.jpin = scanner.nextLine();
            Client3000.isjp=true;

            if(Client3000.jpin.equals("&")){       //上传文件
                Client3000.pathfile=scanner.nextLine();
                Client3000.iscp=true;

            }
        }
    }
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值