服务线程
java
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;
public class ServerReaderThread extends Thread{
private Socket socket;
public ServerReaderThread(Socket socket){
this.socket = socket;
}
@Override
public void run(){
try{
//使用数据输入流 读取 用户发过来的信息
//获取字节输入流
InputStream ipt = socket.getInputStream();
//把原始的字节输入流包装成数据输入流
DataInputStream dis =new DataInputStream(ipt);
while (true){
try{
String rs = dis.readUTF();
System.out.println(rs);
System.out.println("------------------------");
}catch (Exception e){
System.out.println(socket.getRemoteSocketAddress()+"下线...");
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
服务端
java
import java.net.ServerSocket;
import java.net.Socket;
public class Server2 {
public static void main(String[] args) throws Exception{
System.out.println("------------服务端启动--------------");
//创建ServerSocket对象 为服务端注册端口
ServerSocket socketServer =new ServerSocket(7777);
while (true){
//调用accept 方法等待客户端的链接请求
Socket socket = socketServer.accept();
System.out.println(socket.getRemoteSocketAddress()+"上线....");
new ServerReaderThread(socket).start();
}
}
}
客户端
java
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client2 {
public static void main(String[] args) throws Exception {
//创建一个socket 对象 并同时请求与服务端程序的链接
Socket socket = new Socket("127.0.0.1",7777);
//从socket管道中获取字节流 用来发数据给服务端
OutputStream os = socket.getOutputStream();
//把低级的字节输出流 换成数据输出流
DataOutputStream dos = new DataOutputStream(os);
//开始写数据
Scanner sc =new Scanner(System.in);
while (true){
System.out.println("user:");
String msg =sc.nextLine();
if("exit".equals(msg)){
System.out.println("退出会话...");
dos.close();
//释放连接资源
socket.close();
break;
}
dos.writeUTF(msg);
dos.flush();
}
}
}
效果