hdml指的是什么接口
273
2022-11-03
java Socket客户端和服务器端
客户端:
package com.lzx.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;import org.xml.sax.InputSource;public class SocketClient { public static void main(String[] args) { new SocketClient(); } public SocketClient() { try { Socket socket = new Socket("127.0.0.1", 9999); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //接收键盘输入内容 System.out.println("enter some words : "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line = reader.readLine(); out.println(line); //接收服务器端的数据 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("reply from server : " + in.readLine()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
服务器:
package com.lzx.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;public class SocketServer { public static void main(String[] args) { new SocketServer(); } public SocketServer() { try { ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); String remoteHost = serverSocket.getInetAddress().getHostName(); int remotePort = serverSocket.getLocalPort();//客户端端口 System.out.println("A client come, remoteHost :" + remoteHost + ", remotePort : " + remotePort); //接收客户端的数据 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("received from client : " + reader.readLine()); //回复客户端 PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Tanks,I love you!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~