首页 > 代码库 > java--网络编程
java--网络编程
1.Client端
import java.net.* ; import java.io.* ; public class Client { public static void main(String[] args) throws Exception { Socket s = new Socket("localhost",8888); //向服务器发送消息 InputStreamReader r = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(r); System.out.println("Input your want to write : " ); String msg = br.readLine(); OutputStream os = s.getOutputStream(); DataOutputStream ds = new DataOutputStream(os); ds.writeUTF(msg); //接受来自服务器的消息 InputStream r1 = s.getInputStream(); DataInputStream dis = new DataInputStream(r1); String serverMsg = dis.readUTF(); System.out.println("Reverse the Server massage is : " + serverMsg ); br.close(); s.close(); } }
2.Server端
1 import java.net.*; 2 import java.io.* ; 3 4 public class Server { 5 public static void main(String[] args) throws Exception { 6 ServerSocket serverSocket = new ServerSocket(8888); 7 while(true) { 8 9 //接受客户端消息 10 Socket socket = serverSocket.accept(); 11 System.out.println("a client connect this server !"); 12 InputStream r = socket.getInputStream(); 13 14 DataInputStream dis = new DataInputStream(r); 15 String clientMsg = dis.readUTF(); 16 System.out.println("send to this server : " + clientMsg); 17 18 //向客户端回复消息 19 BufferedReader input = new BufferedReader( 20 new InputStreamReader(System.in) 21 ); 22 String backMsg = input.readLine(); 23 OutputStream os = socket.getOutputStream(); 24 DataOutputStream dos = new DataOutputStream(os); 25 dos.writeUTF(backMsg); 26 input.close(); 27 } 28 } 29 }
以上代码实现了点对点的通信。
java--网络编程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。