Socket实现简单聊天
服务端:
package main.java.com.socket_dome; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class LoginServer { public static void main(String[] args) { Scanner input = new Scanner(System.in); ServerSocket serverSocket = null; Socket socket = null; try { //输入提示语,代表服务端成功启动 System.out.println("启动成功!"); //建立客户端,并连接8080端口号 serverSocket = new ServerSocket(8080); //监听客户端 socket = serverSocket.accept(); //打开socket的I/O流 InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); //循环,让服务端一直处于监听状态 while(true){ //接收来自客户端的信息,并且打印在控制台 int len = 0; byte[] b = new byte[1024]; len = is.read(b); System.out.println("客户端说:"+ new String(b,0,len)); System.out.println("服务端输入:"); //把回复的内容打散成字节数组发送给客户端 String reply = input.next(); os.write(reply.getBytes()); } } catch (IOException e) { e.printStackTrace(); }finally { try { //关闭socked,切记不可以关闭i/o流 socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
客户端:
package main.java.com.socket_dome; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.sql.SQLOutput; import java.util.Scanner; public class Clinet { public static void main(String[] args) { Scanner input = new Scanner(System.in); Socket socket = null; OutputStream os = null; InputStream is = null; try { //建立客户端,本机连接测试 socket = new Socket("localhost",8080); //打开输出流 os = socket.getOutputStream(); is = socket.getInputStream(); //不断的来回交互,因此写个死循环 while (true){ //发送信息给客户 System.out.println("客户端输入:"); os.write(input.next().getBytes()); //接收读取的信息 int len = 0 ; byte[] b = new byte[1024]; len = is.read(b); System.out.println("服务器说:"+ new String(b,0,len)); } } catch (IOException e) { e.printStackTrace(); }finally { try { //关闭socket if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
效果: