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 }
以上代码实现了点对点的通信。
在网上看到了一篇文章讲的是网络编程UDP 实现点对点通信。http://computerdragon.blog.51cto.com/6235984/1194280这是网址,可以参考,讲的很详细。