http://www.javaworld.com/javaworld/jw-12-1997/jw-12-step-p2.html

解决方案 »

  1.   

    去搜索:java Socket。程序大把大把的。
      

  2.   

    跟系统无关,关键是你得知道要接收和要发送的数据流所遵循的格式,比如是否有报文头,多少位,数据区是什么样的数据,假如你知道unix服务器首先会发送一个32位的整数,那你将接收到的数据的前32位拿出来转成整数,那就是服务器要给你的数据了。同样的道理,按照一定的格式往服务器传送数据
      

  3.   

    多谢各位,是和系统无关,我只是描述一下,请问那位有好用的相对简单写的多线程的SOCKET程序的例子给我参考以下,因为很急的,以前有没有做过,请大家帮忙!
      

  4.   

    只是一个简单的多线程服务程序,给你作参考。
    因简化原因,请看懂程序并作相应修改之后,才能运行。import java.io.*;
    import java.net.*;
    import java.util.*;public class ProtocolHandler  {   int listenPort = 8001;
       ServerSocket myServer = null;
       JuryThread checkIt;
       Socket answerSocket;   public ProtocolHandler()
    {
            try {
    myServer = new ServerSocket(listenPort);
    while (true) {
                       answerSocket = myServer.accept();
                       checkIt = new JuryThread(answerSocket);
       checkIt.start();

    }catch (Exception e) {}   
        } 
        public static void main(String args[]) {
      new ProtocolHandler();
        }
    }
    class JuryThread extends Thread {

        Socket talkToMe;
        ObjectOutputStream sendStream;
        ObjectInputStream recvStream;
        Command command;
        
        boolean alive = true;
        
        public JuryThread (Socket s){
            talkToMe = s;
            try {
                OutputStream os = talkToMe.getOutputStream();
                InputStream is = talkToMe.getInputStream();
                sendStream = new ObjectOutputStream(os);
                recvStream = new ObjectInputStream(is);
            } catch (IOException e) { 
            }
    }

        public void run() {
            while (alive) {
                try {
                     System.out.println("reading object...");
                    command = (Command)recvStream.readObject();
                     System.out.println("object read.");
                    
                switch (command.getCommandValue())
                {
                    case Command.READCUSTLIST: 
                    {
    ...
                    
                     break;
                    }
                    case Command.ADDACUSTOMER: 
                    {
                        ...
                        
                        break;
                    }
                } // end switch
                
                sendStream.writeObject(command);
                
                } catch (EOFException ex) {             
                 //ex.printStackTrace();
                 System.out.println("Connection closed.");
                 alive = false;
                
                } catch (SocketException ex){
                 //ex.printStackTrace();
                 System.out.println("Connection closed.");
                 alive = false;
                
                } catch (Exception ex) {             
                 ex.printStackTrace();
                }
            }// end while
        } // end run
    } // end JuryThread
      

  5.   

    程序的大意是,每当有客户端连到服务器上时,服务器在取得Socket后,便创建一个线程,并将Socket对象传给他处理,而自身线程随后返回继续监听端口。这个创建的线程将对传来的socket进行处理,直到run方法执行完毕。在JuryThread类中的run方法内,可以循环读取这个客户的多次请求,并根据请求作出响应,直到客户发出退出命令或者断掉连接,run方法结束。
      

  6.   

    testclient.java/*
     * Created on 2004-9-15
     *
     * To change the template for this generated file go to
     * Window>Preferences>Java>Code Generation>Code and Comments
     */
    package socket;/**
     * @author Administrator
     *
     * To change the template for this generated type comment go to
     * Window>Preferences>Java>Code Generation>Code and Comments
     */
    import java.net.*;
    import java.io.*;public class testclient
    {
    public static void main(String[] args)
    {
    Socket asocket;
    int i;
    DataOutputStream dos;
    byte[] buffer;
    while (true)
    {
    try
    {
    asocket = new Socket("127.0.0.1", 1500); dos = new DataOutputStream(asocket.getOutputStream());
    buffer = new byte[512];
    i = System.in.read(buffer);
    dos.write(buffer, 0, i);
    dos.close();
    asocket.close(); }
    catch (Exception e)
    {
    System.out.println("client error");
    }
    }
    }
    }
      

  7.   

    testserver.java/*
     * Created on 2004-9-15
     *
     * To change the template for this generated file go to
     * Window>Preferences>Java>Code Generation>Code and Comments
     */
    package socket;/**
     * @author Administrator
     *
     * To change the template for this generated type comment go to
     * Window>Preferences>Java>Code Generation>Code and Comments
     */
    import java.io.*;
    import java.net.*;public class testserver implements Runnable
    {
    public void run()
    {
    DataInputStream dis;
    Socket asocket;
    while (true)
    {
    try
    {
    ServerSocket aserver = new ServerSocket(1500); asocket = aserver.accept(); dis = new DataInputStream(asocket.getInputStream());
    int read;
    byte[] buffer;
    do
    {
    buffer = new byte[512];
    read = dis.read(buffer);
    String s = new String(buffer, 0, read);
    System.out.println(s);
    }
    while (read != -1);
    dis.close();
    asocket.close(); }
    catch (Exception e)
    {
    System.out.println("server error");
    }
    }
    } public static void main(String[] args)
    { Thread t1 = new Thread(new testserver());
    t1.start(); }}
      

  8.   

    去IBM-developerWorks有java socket的教程
      

  9.   

    我做过一个socket通讯的程序,主要需要考虑的问题是网络传输字节序的问题,具体思路是上边几位一致,可以看一下oreilly的java network programming
      

  10.   

    //客户端
    import java.net.*;
    import java.io.*;class JabberClientThread extends Thread{
       private Socket socket;
       private BufferedReader in;
       private PrintWriter out;
       private static int counter=0;
       private int id=counter++;
       private static int threadcount=0;
       public static int threadCount(){
         return threadcount;
       }public JabberClientThread(InetAddress addr){
        System.out.println("making client"+id);
        threadcount++;
        try{
            socket=new Socket(addr, MultiJabberServer.PORT);
        }catch(IOException e){
         System.err.println("Socket Failed");
         }
        try{
           in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
           out=new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
           start();
        }catch(IOException e){
         try{
             socket.close();
         }catch(IOException e2){
          System.err.println("Scocket not closed");
          }
         }
        }public void run(){
        try{
          for(int i=0;i<25;i++){
            out.println("Client"+id+":"+i);
            String str=in.readLine();
            System.out.println(str);
          }  
          out.println("END");
        }catch(IOException e){
         System.err.println("IO Exception");
         }finally{
          try{
            socket.close();
          }catch(IOException e){
           System.err.println("Socket not closed");
           }
           threadcount--;
          }
          }
    }public class MultiJabberClient{
       static final int MAX_THREADS=40;
       public static void main(String[] args)throws IOException,InterruptedException{
           InetAddress addr=InetAddress.getByName(null);
           while(true){
             if(JabberClientThread.threadCount()<MAX_THREADS)new JabberClientThread(addr);
              Thread.currentThread().sleep(100);
           }
          }    
    }
    //服务器端
    import java.io.*;
    import java.net.*;class ServeOneJabber extends Thread{
      private Socket socket;
      private BufferedReader in;
      private PrintWriter out;
      
     public ServeOneJabber(Socket s) throws IOException{
      socket=s;
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
      start();
     }  public void run(){
      try{
          while(true){
              String str = in.readLine();
              if (str.equals("END")) break;
              System.out.println("Echoing:" + str);
              out.println(str);
          }
            System.out.println("closing...");
                
          }catch(IOException e){
           System.err.println("IO Exception");
          }finally{
           try{
               socket.close();
           }catch(IOException e){
            System.err.println("Socket not closed");
            }
           }
     }
    } public class MultiJabberServer{
       static final int PORT=8080;
       public static void main(String[] args)throws IOException{
          ServerSocket s=new ServerSocket(PORT);
          System.out.println("Server Started");
       try{
           while(true){
            Socket socket=s.accept();
            try{
                new ServeOneJabber(socket);
            }catch(IOException e){
             socket.close();
             }
           }
        }finally{
         s.close();
         }
      }
    }
    //这个程序我调试通过的,你自己仔细看懂哦,希望可以帮上你.
      

  11.   

    thinking in java上说的很简单易懂的!建议看看!
      

  12.   

    不行,有个好例子非举不可,哈哈
    简单的服务器这个服务器所做的全部工作是在留式连接上发送字符串 "Hello, World!\n"。你要 测试这个程序的话,可以在一台机器上运行该程序,然后在另外一机器上登陆:   $ telnet remotehostname 3490remotehostname 是该程序运行的机器的名字。服务器代码:   #include <stdio.h>   #include <stdlib.h>   #include <errno.h>   #include <string.h>   #include <sys/types.h>   #include <netinet/in.h>   #include <sys/socket.h>   #include <sys/wait.h>   #define MYPORT 3490    /* the port users will be connecting to */   #define BACKLOG 10     /* how many pending connections queue will hold */   main()   {       int sockfd, new_fd;  /* listen on sock_fd, new connection on new_fd */       struct sockaddr_in my_addr;    /* my address information */       struct sockaddr_in their_addr; /* connector's address information */       int sin_size;       if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {           perror("socket");           exit(1);       }       my_addr.sin_family = AF_INET;         /* host byte order */       my_addr.sin_port = htons(MYPORT);     /* short, network byte order */       my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */       bzero(&(my_addr.sin_zero), 8);        /* zero the rest of the struct */       if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \                   == -1) {           perror("bind");           exit(1);       }       if (listen(sockfd, BACKLOG) == -1) {           perror("listen");           exit(1);       }       while(1) {  /* main accept() loop */           sin_size = sizeof(struct sockaddr_in);           if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \                    &sin_size)) == -1) {               perror("accept");               continue;           }           printf("server: got connection from %s\n", \                                              inet_ntoa(their_addr.sin_addr));           if (!fork()) { /* this is the child process */               if (send(new_fd, "Hello, world!\n", 14, 0) == -1)                   perror("send");               close(new_fd);               exit(0);           }           close(new_fd);  /* parent doesn't need this */           while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */       }   }如果你很挑剔的话,一定不满意我所有的代码都在一个很大的 main() 函数 中。如果你不喜欢,可以划分得更细点。你也可以用我们下一章中的程序得到服务器端发送的字符串。
      

  13.   

    --------------------------------------------------------------------------------简单的客户程序这个程序比服务器还简单。这个程序的所有工作是通过 3490 端口连接到命令行中制定的主机, 然后得到服务器的字符串。客户代码:   #include <stdio.h>   #include <stdlib.h>   #include <errno.h>   #include <string.h>   #include <netdb.h>   #include <sys/types.h>   #include <netinet/in.h>   #include <sys/socket.h>   #define PORT 3490    /* the port client will be connecting to */   #define MAXDATASIZE 100 /* max number of bytes we can get at once */   int main(int argc, char *argv[])   {       int sockfd, numbytes;         char buf[MAXDATASIZE];       struct hostent *he;       struct sockaddr_in their_addr; /* connector's address information */       if (argc != 2) {           fprintf(stderr,"usage: client hostname\n");           exit(1);       }       if ((he=gethostbyname(argv[1])) == NULL) {  /* get the host info */           herror("gethostbyname");           exit(1);       }       if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {           perror("socket");           exit(1);       }       their_addr.sin_family = AF_INET;      /* host byte order */       their_addr.sin_port = htons(PORT);    /* short, network byte order */       their_addr.sin_addr = *((struct in_addr *)he->h_addr);       bzero(&(their_addr.sin_zero), 8);     /* zero the rest of the struct */       if (connect(sockfd, (struct sockaddr *)&their_addr, \                                             sizeof(struct sockaddr)) == -1) {           perror("connect");           exit(1);       }       if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {           perror("recv");           exit(1);       }       buf[numbytes] = '\0';       printf("Received: %s",buf);       close(sockfd);       return 0;   }注意,如果你在运行服务器之前运行客户程序,connect() 将返回 "Connection refused" 信息。