服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

一个完整的socket例子


  以下程序在jbuilder4下调试成功![下载源程序]
  服务端的程序:
  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();
  }
  }

扫描关注微信公众号