JavaSocket联机通讯

jackxiang 2006-9-23 16:58 | |
以前觉得asp&php的书上写的是网络编程,其实本人认为socket才是的,比如java c # perl等才有的,本人用eclips随便调写了一个程序如下:

1.Clent端code:

import java.io.*;
import java.net.*;
public class Client
{
  public static void main(String[] args)
  {
    // TODO Auto-generated method stub
    
      String s=null;
      Socket mysocket;
      DataInputStream in=null;
      DataOutputStream out=null;
      try
      {
        mysocket=new Socket("localhost",4331);
      
      in=new DataInputStream(mysocket.getInputStream());
      out=new DataOutputStream(mysocket.getOutputStream());
      out.writeUTF("你好·");//
      while(true){
        s=in.readUTF();
        out.writeUTF(":"+Math.random());
        Thread.sleep(500);
        
                }
                
      }
      catch(IOException e)
      {
        System.out.print("无法联接!");
        
        
      }
      catch(InterruptedException e){}
      
      
      
      
    }

}

2.server端程序:



import java.io.*;
import java.net.*;
public class Server
{

  /**
   * @param args
   */
  public static void main(String[] args)
  {
    // TODO Auto-generated method stub
    ServerSocket server=null;
    Socket you=null;String s=null;
    DataOutputStream out=null;DataInputStream in=null;
    try
    {
      server=new ServerSocket(4331);
        
      
    }
    
    catch(IOException el){System.out.print("Erro:"+el); }
    try  {you=server.accept();
    
    in=new DataInputStream(you.getInputStream());
    out=new DataOutputStream(you.getOutputStream());
    while(true)
    {
      s=in.readUTF();
      out.writeUTF("你好,我是服务中心");
      out.writeUTF("你说的是:"+s);
      System.out.print("服务中心收到:"+s);
      Thread.sleep(500);
        
      
      
    }
      
      
  }
    catch(IOException e)
       {
      System.out.print(""+e);
      
       }
    catch(InterruptedException e){}
    
    
  }

}

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/164/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]