首页 > 代码库 > ServerSocket 和 ClientSocket (网络编程)
ServerSocket 和 ClientSocket (网络编程)
TestServerSocket.java
package com.sxt.net; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /* * 服务端 */ public class TestServerSocket { public static void main(String[] args) throws IOException { System.out.println("服务端准备就绪"); //服务端 ServerSocket server = new ServerSocket(8888); //获取客户端的Socket Socket accept = server.accept(); //获取客户端的输入流 InputStream inputStream = accept.getInputStream(); DataInputStream dis = new DataInputStream(inputStream); //输入流读取到程序中 String readUTF = dis.readUTF(); //客户端信息显示在控制台 System.out.println(readUTF); //通过输出流发送数据回应客户端 OutputStream outputStream = accept.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputStream); //输出流写到客户端 dos.writeUTF("打招呼干嘛呢"); accept.close(); server.close(); } }
TestClientSocket.java
package com.sxt.net; import java.io.DataInputStream; import java.io.DataOutputStream; /* * 客户端 */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class TestClientSocket { public static void main(String[] args) throws UnknownHostException, IOException { //指定发送服务端的主机IP 端口号 Socket socket = new Socket(InetAddress.getLocalHost(), 8888); //通过输出流向服务端发送数据 OutputStream outputStream = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputStream); //将数据写出到服务端 dos.writeUTF("客户端:你好 老兄"); //通过输入流读取服务端的回应信息 InputStream inputStream = socket.getInputStream(); DataInputStream dis = new DataInputStream(inputStream); //读取流到程序 String readUTF = dis.readUTF(); //显示到控制台 System.out.println(readUTF); socket.close(); } }
ServerSocket 和 ClientSocket (网络编程)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。