简单的socket通讯学习,1对1聊天
程序员文章站
2022-03-01 21:26:03
...
1:简单介绍Socket和ServerSocket的通信,如下,注意客户端和服务是怎么交换数据的
1:客户端代码
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class Client { private static int port = 12315; // 端口 private static String address = "localhost"; public void chat() throws IOException { try { Socket socket = new Socket(address, port); // 连接到服务器. try { // 获得从服务端发送过来的信息 DataInputStream din = new DataInputStream(socket .getInputStream()); // 声明想发送到服务器的输出流 DataOutputStream dout = new DataOutputStream(socket .getOutputStream()); Scanner scan = new Scanner(System.in); // 获得客户端输入的信息 while (true) { String sendMsg = scan.nextLine(); if (!"".equals(sendMsg)) { System.out.println("****客户端: " + sendMsg + " "); dout.writeUTF(sendMsg); String recvMsg = din.readUTF(); if (null != recvMsg) { System.out.println("***服务端: " + recvMsg + " "); } } } } finally { socket.close(); } } finally { } } public static void main(String[] aregs) throws IOException{ new Client().chat(); } }
2: 服务端代码
import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class HostServer { private static int port = 12315; public void service(){ try{ ServerSocket server = new ServerSocket(port); //建立服务器连接 Socket socket = server.accept(); //等待客户端连接 try{ DataInputStream din = new DataInputStream(socket.getInputStream()); //获得客户端输入流 DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); //取得输出流 Scanner scan = new Scanner(System.in); while(true){ String recvMsg = din.readUTF(); //获得客户端发送的信息 System.out.println("------客户端:" + recvMsg); String sendMsg = scan.nextLine(); System.out.println("------服务端:" + sendMsg); dout.writeUTF(sendMsg); //将从控制台读取的数据发送给客户端 } }finally{ socket.close(); } }catch (Exception e) { } } public static void main(String[] args){ new HostServer().service(); } }
先运行HostServer,在运行Client,
这个程序满足1对1的信息交互,
上一篇: iBatis简单入门教程
下一篇: css3动画实现旋转木马