java 网络编程Socket编程
Posted 我有一壶酒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 网络编程Socket编程相关的知识,希望对你有一定的参考价值。
Server.java
import java.io.*; import java.net.*; public class Server { public static void main(String args[]) { String [] answer ={"南非","进入世界杯了","哈哈...问题真逗!"}; ServerSocket serverForClient=null; Socket socketOnServer=null; DataOutputStream out=null; DataInputStream in=null; try { serverForClient = new ServerSocket(2010); } catch(IOException e1) { System.out.println(e1); } try{ System.out.println("等待客户呼叫"); socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫 out=new DataOutputStream(socketOnServer.getOutputStream()); in=new DataInputStream(socketOnServer.getInputStream()); for(int i=0;i<answer.length;i++) { String s=in.readUTF(); // in读取信息,堵塞状态 System.out.println("服务器收到客户的提问:"+s); out.writeUTF(answer[i]); Thread.sleep(500); } } catch(Exception e) { System.out.println("客户已断开"+e); } } }
Client.java
import java.io.*; import java.net.*; public class Client { public static void main(String args[]) { String [] mess ={"2010世界杯在哪举行?","巴西进入世界杯了码?","中国进入世界杯了码?"}; Socket mysocket; DataInputStream in=null; DataOutputStream out=null; try{ mysocket=new Socket("127.0.0.1",2010); in=new DataInputStream(mysocket.getInputStream()); out=new DataOutputStream(mysocket.getOutputStream()); for(int i=0;i<mess.length;i++) { out.writeUTF(mess[i]); String s=in.readUTF(); //in读取信息,堵塞状态 System.out.println("客户收到服务器的回答:"+s); Thread.sleep(500); } } catch(Exception e) { System.out.println("服务器已断开"+e); } } }
以上是关于java 网络编程Socket编程的主要内容,如果未能解决你的问题,请参考以下文章