网络编程多线程IO流通过多线程和IO流实现服务器与客户端互动对话

tech2026-06-15  2

服务器部分:

package com.softeem.inetAddress; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JOptionPane; public class Test4_server { public static void main(String[] args) throws IOException { //创建一个套接字插座 ServerSocket ss = new ServerSocket(6666); System.out.println("等待客户端连接。。。。"); Socket s = ss.accept(); //返回客户端的socket对象 System.out.println("连接成功!"); //实例化Message1类对象 Message1 m = new Message1(s); //启动线程 new Thread(m,"发送").start(); new Thread(m,"接收").start(); } } //线程类,实现发送和接收消息 class Message1 implements Runnable{ Socket s; public Message1(Socket s){ this.s = s; } public void run() { String name = Thread.currentThread().getName(); //判断当前线程名并采取相对应的操作 try { if(name.equals("发送")){ //发送消息的方法 while(true){ //创建数据输出流包装需要发送的的OutputStream对象 DataOutputStream dos = new DataOutputStream(s.getOutputStream()); //System.out.println("请输入你需要发送的消息:"); String str = JOptionPane.showInputDialog("请输入你需要发送的消息:"); //使用弹窗作为输入界面可以避免eclipse控制台的bug System.out.println("服务器:"+str); //显示记录自己发送的消息 dos.writeUTF(str); } }else{ //接收消息的方法 while(true){ //创建数据输入流包装从客户端接收到的InputStream对象 DataInputStream dis = new DataInputStream(s.getInputStream()); System.out.println("从客户端读取了:"+dis.readUTF()); } } } catch (IOException e) { e.printStackTrace(); } } }

客户端部分:

package com.softeem.inetAddress; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JOptionPane; public class Test4_client { public static void main(String[] args) throws UnknownHostException, IOException { //创建一个插头 Socket s = new Socket("192.168.5.113",6666); //实例化Message2类对象 Message2 m = new Message2(s); //启动线程 new Thread(m,"接收").start(); new Thread(m,"发送").start(); } } class Message2 implements Runnable{ Socket s; public Message2(Socket s){ this.s = s; } public void run() { String name = Thread.currentThread().getName(); //判断当前线程名并采取相对应的操作 try { if(name.equals("接收")){ //接收消息的方法 while(true){ //创建数据输入流包装从客户端接收到的InputStream对象 DataInputStream dis = new DataInputStream(s.getInputStream()); System.out.println("从服务器读取了:"+dis.readUTF()); } }else{ //发送消息的方法 while(true){ //创建数据输出流包装需要发送的的OutputStream对象 DataOutputStream dos = new DataOutputStream(s.getOutputStream()); //System.out.println("请输入你需要发送的消息:"); String str = JOptionPane.showInputDialog("请输入你需要发送的消息:"); //使用弹窗作为输入界面可以避免eclipse控制台的bug System.out.println("服务器:"+str); //显示记录自己发送的消息 dos.writeUTF(str); } } } catch (IOException e) { e.printStackTrace(); } } }
最新回复(0)