线程代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread{
// 和本线程相关的socket
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
// 线程执行的操作,响应客服端请求
public void run() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try {
// 3.获取输入流,并读取客服端信息
is = socket.getInputStream();//字节输入流
isr = new InputStreamReader(is);//将字节流转换为字符流
br = new BufferedReader(isr);//为输入流添加缓冲
String info = null;
String infoResult = "";
String sendString="";
while ((info=br.readLine())!=null) {//循环读取客服端的信息
infoResult = infoResult+info;
}
socket.shutdownInput();//关闭输入流
//=====================================================
System.out.println(" In:"+infoResult);
// 4.响应客服端 即给客服端发送信息
os = socket.getOutputStream();//字节输出流
pw = new PrintWriter(os);//将输出流包装为打印流
//sendString = Integer.toString(BiaoQian);
pw.write(sendString);// 写入客户端的信息+只能是纯数字字符串
System.out.println("Out:"+sendString);
pw.flush();//调用flush()方法将缓冲输出
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
// 5.关闭资源
if (pw!=null) {pw.close();}
if (os!=null) {os.close();}
if (br!=null) {br.close();}
if (isr!=null) {isr.close();}
if (is!=null) {is.close(); }
if (socket!=null) {socket.close();}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}