首页 > 编程 > Java > 正文

JavaSocket简单通信

2019-11-08 02:06:07
字体:
来源:转载
供稿:网友

以下介绍:简单的socket发送消息,服务的Server 相互 客户端Client,进行简单的传递消息:


服务端代码:

package test;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class Server { /** * 服务器连接的Socket */ public static ServerSocket cServerSocket; /** * 连接 */ public static Socket cSocket; /** * 端口 */ public static final int PORT = 8888; public static void main(String[] args) { DataInputStream dis = null; DataOutputStream dos = null; try { cServerSocket = new ServerSocket(PORT); while (true) { System.out.PRintln("正在等待客户连接..."); // 这里处于等待状态,如果没有客户端连接,程序不会向下执行 cSocket = cServerSocket.accept(); dis = new DataInputStream(cSocket.getInputStream()); dos = new DataOutputStream(cSocket.getOutputStream()); // 读取数据 String clientStr = dis.readUTF(); String msg = "已收到信息:"+clientStr; // 写出数据 dos.writeUTF(msg); System.out.println(msg); System.out.println("---客户端信息打印,ip:" + cSocket.getInetAddress() + " Prot:" + cSocket.getPort()); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (dis != null) { dis.close(); } if (dos != null) { dos.close(); } } catch (IOException e) { e.printStackTrace(); } } }}

客户端代码:

private Socket cSocket;// 服务器server/IP地址(当前PC的IP地址)private final String ADDRESS = "192.168.8.2";// 服务器端口private final int PORT = 8888;cThread = new Thread() {@Overridepublic void run() { super.run(); DataInputStream dis = null; DataOutputStream dos = null; try { // 阻塞函数,正常连接后才会向下继续执行 cSocket = new Socket(ADDRESS, PORT); dis = new DataInputStream(cSocket.getInputStream()); dos = new DataOutputStream(cSocket.getOutputStream()); // 向服务器写数据 dos.writeUTF("hello socket..."); // 读取服务器发来的数据 cContent += dis.readUTF(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (dis != null) { dis.close(); } if (dos != null) { dos.close(); } } catch (IOException e) { e.printStackTrace(); } }; cThread.start();

运行效果: 这里写图片描述


谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问, 刘德利CSDN博客, http://blog.csdn.net/u011967006


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表