java网络编程
服务器端:
import java.io.*; import java.net.*; public class project { public static void main(String[] args) { ServerSocket server=null; Socket you=null; DataOutputStream out=null; DataInputStream in=null; try{ server=new ServerSocket(4331); }catch(IOException e1){ System.out.println(e1); } try{ System.out.println("等待客户呼叫"); you=server.accept(); out=new DataOutputStream(you.getOutputStream()); in=new DataInputStream(you.getInputStream()); while(true){ char c=in.readChar(); System.out.println("服务器收到: "+c); out.writeChar((char)(c-32)); Thread.sleep(500); } }catch(Exception e){ System.out.println("客户端已断开"+e); } } }
客户端:
import java.net.*; import java.io.*; public class project{ public static void main(String args[]){ Socket mysocket; DataInputStream in=null; DataOutputStream out=null; try{ mysocket=new Socket("127.0.0.1",4331); in=new DataInputStream(mysocket.getInputStream()); out=new DataOutputStream(mysocket.getOutputStream()); char c='a'; while(true) { if(c>'z') c='a'; out.writeChar(c); char s=in.readChar(); System.out.println("客户收到:"+s); c++; Thread.sleep(500); } }catch(Exception e){ System.out.println("服务器已经断开"); } } }
实验结果:
开启服务:
请求服务: