1 // 客户端程序 2 import java.io.*; 3 import java.net.ServerSocket; 4 import java.net.Socket; 5 6 public class user{ 7 public static void main(String[] args) throws InterruptedException { 8 String s = null; 9 Socket mysocket; 10 DataOutputStream out = null; 11 DataInputStream in = null; 12 int i =1; 13 try { 14 mysocket= new Socket("localhost",4331); 15 in = new DataInputStream(mysocket.getInputStream()); 16 out = new DataOutputStream(mysocket.getOutputStream()); 17 out.writeInt(i); 18 while(true){ 19 i = (i+1)%128; 20 s = in.readUTF(); 21 out.writeInt(i); 22 System.out.println("客户收到:"+s); 23 Thread.sleep(500); 24 } 25 }catch(IOException e) { 26 27 } 28 } 29 }
1 //服务器端程序 2 import java.io.*; 3 import java.net.ServerSocket; 4 import java.net.Socket; 5 6 public class Test2{ 7 public static void main(String[] args){ 8 ServerSocket server = null; 9 Socket you = null; 10 DataOutputStream out = null; 11 DataInputStream in = null; 12 13 try{ 14 server = new ServerSocket(4331); 15 16 }catch(IOException e1){} 17 18 try{ 19 you = server.accept(); 20 in = new DataInputStream(you.getInputStream()); 21 out = new DataOutputStream(you.getOutputStream()); 22 while(true) 23 { 24 int m = 0; 25 m = in.readInt(); 26 out.writeUTF("你说的对应数字为:" + (char)m); 27 } 28 }catch(IOException e2) { } 29 30 // catch(InterruptedException e) { } 31 32 33 } 34 }
本文提供了一个Java网络编程的实例,包括客户端和服务器端的代码。客户端通过Socket连接到本地主机的4331端口,与服务器进行数据交换。服务器接收来自客户端的数据,并将接收到的数字转换为字符后返回给客户端。

8615

被折叠的 条评论
为什么被折叠?



