Socket网络编程

xiaoxiao2021-02-28  2

服务器端创建 ServerSocket对象管理 ServerSocket s = new ServerSocket(端口号); 有一个监听客户端请求的方法:Socket accept(); 如果有客户端Socket1连接,那么将返回一个与客户端Socket对应的Socket2 ServerSocket s = new ServerSocket(端口号); While(true){ //如果没有客户端Socket发送连接请求,那么该方法将一直处于等待状态 Socket a = s.accept(); //接下来就可以进行Socket通信了 例如下面实现服务器与客户端简单的连接

package serversocket; import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(30013); while(true) { Scanner sc = new Scanner(System.in); Socket s = ss.accept(); PrintStream ps = new PrintStream(s.getOutputStream()); ps.println(System.currentTimeMillis()+"这里是服务器"); while(sc.hasNextLine()) { ps.println(sc.nextLine()); } sc.close(); ps.close(); s.close(); } } } package serversocket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1",30013); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("来自服务器127.0.0.1,端口号为30000的数据"); String s = null; while((s=br.readLine())!=null) { System.out.println(s); } br.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
转载请注明原文地址: https://www.6miu.com/read-1400394.html

最新回复(0)