封装IO

package Client;

import java.io.DataInputStream;

import java.io.IOException;

import java.net.Socket;

/**

* 接受数据线程

*

*

*/

public class Receiveimplements Runnable {

//输入流

    private DataInputStreamdis;

//线程状态标识

    private  boolean isRunning =true;

public Receive(){

}

public Receive(Socket client){

try {

dis=new DataInputStream(client.getInputStream());

}catch (IOException e) {

//e.printStackTrace();

            isRunning=false;

Closeutil.closeAll(dis);

}

}

//接收数据的方法

    public String receive(){

String rec="";

try {

rec=dis.readUTF();

}catch (IOException e) {

//e.printStackTrace();

            isRunning=false;

Closeutil.closeAll(dis);

}

return rec;

}

@Override

    public void run() {

//线程体

        while (isRunning){

System.out.println(receive());

}

}

}



package Client;

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.Socket;

/**

* 发送线程

*进行封装

*/

public class Sendimplements Runnable{

//控制台输出

    private BufferedReaderconsole;

// socketI/O流

    private DataOutputStreamdos;

//线程是否运行中

    private boolean isRunning=true;

public Send() {

console=new BufferedReader(new InputStreamReader(System.in));

}

public Send(Socket client){

this();

try {

dos=new DataOutputStream(client.getOutputStream());

}catch (IOException e) {

// e.printStackTrace();

            isRunning=false;

Closeutil.closeAll(dos,console);

}

}

// 从控制台接收数据

    private String getConsole(){

try {

return console.readLine();

}catch (IOException e) {

// e.printStackTrace();

        }

return "";

}

/**

    * 从控制台接收数据

    * 发送数据

    */

    public void send(){

String cos=getConsole();

if (cos!=null&&cos.equals("")){

try {

dos.writeUTF(cos);

dos.flush();//强制刷新

            }catch (IOException e) {

//e.printStackTrace();

                isRunning=false;

Closeutil.closeAll(dos,console);

}

}

}

@Override

    public void run() {

//线程体

        while (isRunning){

send();

}

}

}


package Client;

import java.io.Closeable;

import java.io.IOException;

/**

* 关闭流的方法

*/

public class Closeutil {

public  static void closeAll(Closeable... io){

for (Closeable temp:io){

if (null!=temp){

try {

temp.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

你可能感兴趣的:(封装IO)