java socketserver多线程_java socket 通信socketServer 服务端多线程

线程代码

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

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值