Java Socket通信双向
作者:网络转载 发布时间:[ 2016/3/8 10:38:53 ] 推荐标签:编程语言 测试开发技术
新建两个工程,一个客户端,一个服务端,先启动服务端再启动客户端
两个工程的读写操作线程类基本上完全相同
服务端:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 8000;//监听的端口号
public static void main(String[] args) {
Server server = new Server();
server.init();
}
public void init() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
while (true) {
Socket client = serverSocket.accept();
//一个客户端连接开户两个线程处理读写
new Thread(new ReadHandlerThread(client)).start();
new Thread(new WriteHandlerThread(client)).start();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(serverSocket != null){
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
*处理读操作的线程
*/
class ReadHandlerThread implements Runnable{
private Socket client;
public ReadHandlerThread(Socket client) {
this.client = client;
}
@Override
public void run() {
DataInputStream dis = null;
try{
while(true){
//读取客户端数据
dis = new DataInputStream(client.getInputStream());
String reciver = dis.readUTF();
System.out.println("客户端发过来的内容:" + reciver);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(dis != null){
dis.close();
}
if(client != null){
client = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 处理写操作的线程
*/
class WriteHandlerThread implements Runnable{
private Socket client;
public WriteHandlerThread(Socket client) {
this.client = client;
}
@Override
public void run() {
DataOutputStream dos = null;
BufferedReader br = null;
try{
while(true){
//向客户端回复信息
dos = new DataOutputStream(client.getOutputStream());
System.out.print("请输入: ");
// 键盘录入
br = new BufferedReader(new InputStreamReader(System.in));
String send = br.readLine();
//发送数据
dos.writeUTF(send);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(dos != null){
dos.close();
}
if(br != null){
br.close();
}
if(client != null){
client = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11