LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 672|回复: 0

如何实现socket通讯传输字符串功能??

[复制链接]
发表于 2005-5-18 21:42:00 | 显示全部楼层 |阅读模式
请问如何使下列代码实现传输字符串功能

server端:

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(10001);
        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();
    }
}
client端:

public void SocketClient_01() {
     try{
       init();
       waitData();
     }
     catch(Exception e){
       System.out.println(e.toString());
     }
  }
  
  void init() throws Exception{
        System.out.print("lease enter server ip address:");
        String ip = new String(stdin.readLine());
        s=new Socket(ip,10001);
        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;
      }
    }
  }
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表