国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

一個完整的Socket例子

2019-11-18 12:13:04
字體:
供稿:網(wǎng)友

  以下程序在Jbuilder4下調(diào)試成功![下載源程序]
  服務(wù)端的程序:
  import java.io.*;
  import java.net.*;
  
  public class SocketServer {
  ServerSocket ss=null;
  Socket s=null;
  DataInputStream inStream=null;
  DataOutputStream outStream=null;
  
  public SocketServer() {
  try{
  init();
  }
  catch(Exception e){
  System.out.PRintln(e.toString());
  }
  }
  
  void init() throws Exception{
  ss=new ServerSocket(765);
  s.setSoTimeout(3000);
  }
  
  void waitForClient(){
  try{
  s=ss.accept();
  inStream=new DataInputStream(s.getInputStream());
  outStream=new DataOutputStream(s.getOutputStream());
  outStream.writeUTF("1");
  s.setSoTimeout(3000);
  waitData();
  }
  catch(Exception e){
  System.out.println(e.toString());
  }
  }
  
  void waitData(){
  while(true){
  try{
  String str=inStream.readUTF();
  System.out.println("Server accept: "+str);
  int nu=Integer.parseInt(str)+1;
  if(nu>20){
  System.out.println("Send end!");
  break;
  }
  else{
  str=Integer.toString(nu);
  outStream.writeUTF(str);
  }
  }
  catch(Exception e){
  System.out.println(e.toString());
  break;
  }
  }
  }
  
  public static void main(String[] args) {
  SocketServer socketServer1 = new SocketServer();
  socketServer1.waitForClient();
  }
  }
  
  客戶端的程序:
  
  
  import java.net.*;
  import java.io.*;
  
  public class SocketClient{
  Socket s=null;
  DataInputStream inStream=null;
  DataOutputStream outStream=null;
  
  public SocketClient() {
  try{
  init();
  waitData();
  }
  catch(Exception e){
  System.out.println(e.toString());
  }
  }
  
  void init() throws Exception{
  s=new Socket("192.168.0.32",765); //把這里的ip改成你運行SocketServer.class的IP
  inStream=new DataInputStream(s.getInputStream());
  outStream=new DataOutputStream(s.getOutputStream());
  s.setSoTimeout(3000);
  }
  
  void waitData(){
  while(true){
  try{
  String str=inStream.readUTF();
  System.out.println("Client accept: "+str);
  str=Integer.toString(Integer.parseInt(str)+1);
  outStream.writeUTF(str);
  }
  catch(Exception e){
  System.out.println(e.toString());
  break;
  }
  }
  }
  
  public static void main(String[] args) {
  SocketClient socketClient1 = new SocketClient();
  }
  }

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 如皋市| 舒城县| 商水县| 佛冈县| 临朐县| 普定县| 密山市| 开封县| 和龙市| 铜山县| 民勤县| 沂水县| 抚宁县| 东平县| 新竹市| 绥芬河市| 莒南县| 上蔡县| 长武县| 鄂伦春自治旗| 法库县| 曲周县| 丘北县| 台东县| 乐亭县| 朔州市| 达拉特旗| 涞水县| 伊吾县| 宜春市| 洪洞县| 五峰| 富民县| 郯城县| 丽江市| 淮安市| 保德县| 安塞县| 盐池县| 尼玛县| 南漳县|