2 kakaxi2046 Kakaxi2046 于 2015.07.22 09:54 提问

请问下面这个程序,在不改变功能的前提下,可以改装成多线程运行吗?*请贴上代码,谢谢*

import java.net.*; // for Socket, ServerSocket, and InetAddress
import java.io.*; // for IOException and Input/OutputStream

public class Server {
private static final int BUFSIZE = 32; // Size of receive buffer

public static void main(String[] args) throws IOException {
    if (args.length != 1) // Test for correct # of args
        throw new IllegalArgumentException("Parameter(s): <Port>");

    int servPort = Integer.parseInt(args[0]);

    // Create a server socket to accept client connection requests
    ServerSocket servSock = new ServerSocket(servPort);

    int recvMsgSize; // Size of received message

    byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer

    for (;;) { // Run forever, accepting and servicing connections
        Socket clntSock = servSock.accept(); // Get client connection

        System.out.println("Handling client at "
                           + clntSock.getInetAddress().getHostAddress() + " on port "
                           + clntSock.getPort());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        // Receive until client closes connection, indicated by -1 return
        while ((recvMsgSize = in.read(byteBuffer)) != -1) {

            byte[] changeOrder = changeOrder(byteBuffer, recvMsgSize);
            out.write(changeOrder, 0, recvMsgSize);
        }

        clntSock.close(); // Close the socket. We are done with this client!
    }
    /* NOT REACHED */
}

/*
  change order, for example input <code>abc</code> then output <code>cba</code>
 */

private static byte[] changeOrder(byte[] byteBuffer, int recvMsgSize) {
    byte[] result = new byte[recvMsgSize];
    for (int i = 0; i < recvMsgSize; i++) {
        result[i] = byteBuffer[recvMsgSize - 1 - i];
    }
    return result;
}

}

5个回答

tongyi55555
tongyi55555   2015.07.22 14:15
已采纳

好熟悉的代码啊,呵呵,写了个测试样例你试试,包含客户端和服务端两个部分:

服务端改成:


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerThread extends Thread {
    ServerSocket server = null;

    TcpServerThread() {
        try {
            server = new ServerSocket(12345);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) { // just for listening forever
            try {
                Socket sk = server.accept();
                System.out.println("Handling client at "
                        + sk.getInetAddress().getHostAddress() + " on port "
                        + sk.getPort());
                ServerThread st = new ServerThread(sk);
                st.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new TcpServerThread().start();
    }
}

class ServerThread extends Thread {
    Socket socket = null;
    int recvMsgSize; // Size of received message

    byte[] byteBuffer = new byte[1024]; // Receive buffer

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream in;
        try {
            in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Receive until client closes connection, indicated by -1 return
            while ((recvMsgSize = in.read(byteBuffer)) != -1) {
                /*
                 * (添加代码,企图改变字符串顺序)
                 */
                byte[] changeOrder = changeOrder(byteBuffer, recvMsgSize);
                out.write(changeOrder, 0, recvMsgSize);
            }

            socket.close(); // Close the socket. We are done with this client!
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * change order, for example input <code>abc</code> then output
     * <code>cba</code>
     * 
     * @param byteBuffer
     *            receive bytes
     * @param recvMsgSize
     *            valid length of the receive bytes, cannot larger than
     *            byteBuffer's length.
     * @return
     */
    private byte[] changeOrder(byte[] byteBuffer, int recvMsgSize) {
        byte[] result = new byte[recvMsgSize];
        for (int i = 0; i < recvMsgSize; i++) {
            result[i] = byteBuffer[recvMsgSize - 1 - i];
        }
        return result;
    }
}

客户端改成:



import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class TcpClientThread extends Thread {

    private String server = "localhost";
    private int servPort = 12345;
    private byte[] byteBuffer;
    private static String[] strs = { "abc", "def", "ghki", "uyio", "zysf" };

    public TcpClientThread(String str) {
        byteBuffer = str.getBytes();
    }

    @Override
    public void run() {
        Socket socket;
        try {
            socket = new Socket(server, servPort);
            System.out.println("Connected to server...sending echo string");

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            out.write(byteBuffer); // Send the encoded string to the server

            // Receive the same string back from the server
            int totalBytesRcvd = 0; // Total bytes received so far
            int bytesRcvd; // Bytes received in last read
            while (totalBytesRcvd < byteBuffer.length) {
                if ((bytesRcvd = in.read(byteBuffer, totalBytesRcvd,
                        byteBuffer.length - totalBytesRcvd)) == -1)
                    throw new SocketException("Connection close prematurely");
                totalBytesRcvd += bytesRcvd;
            }

            System.out.println("Received: " + new String(byteBuffer));

            socket.close(); // Close the socket and its streams
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new TcpClientThread(strs[i]).start();
        }
    }

}

shanyingliu
shanyingliu   2015.07.22 10:22

public static void main(String[] args) throws IOException {

         if (args.length != 1) // Test for correct # of args
                throw new IllegalArgumentException("Parameter(s): <Port>");

            int servPort = Integer.parseInt(args[0]);

            // Create a server socket to accept client connection requests
            ServerSocket servSock = new ServerSocket(servPort);

            int recvMsgSize; // Size of received message

            byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer

            for (;;) { // Run forever, accepting and servicing connections
                Thread th=new Thread(){
                    public void run(){
                Socket clntSock = servSock.accept(); // Get client connection
                System.out.println("Handling client at "
                                   + clntSock.getInetAddress().getHostAddress() + " on port "
                                   + clntSock.getPort());

                InputStream in = clntSock.getInputStream();
                OutputStream out = clntSock.getOutputStream();

                // Receive until client closes connection, indicated by -1 return
                while ((recvMsgSize = in.read(byteBuffer)) != -1) {

                    byte[] changeOrder = changeOrder(byteBuffer, recvMsgSize);
                    out.write(changeOrder, 0, recvMsgSize);
                }

                clntSock.close(); // Close the socket. We are done with this client!
                    }
        /*
          change order, for example input <code>abc</code> then output <code>cba</code>
         */
        private byte[] changeOrder(byte[] byteBuffer, int recvMsgSize) {
            byte[] result = new byte[recvMsgSize];
            for (int i = 0; i < recvMsgSize; i++) {
                result[i] = byteBuffer[recvMsgSize - 1 - i];
            }
            return result;
        }
        };
         th.start();
    }
Kakaxi2046
Kakaxi2046 谢谢你的代码,不过无法编译啊。
接近 3 年之前 回复
danielinbiti
danielinbiti   Ds   Rxr 2015.07.22 09:56
shanyingliu
shanyingliu   2015.07.22 10:18

public static void main(String[] args) throws IOException {
Thread th=new Thread(){
public void run(){

         if (args.length != 1) // Test for correct # of args
                throw new IllegalArgumentException("Parameter(s): <Port>");

            int servPort = Integer.parseInt(args[0]);

            // Create a server socket to accept client connection requests
            ServerSocket servSock = new ServerSocket(servPort);

            int recvMsgSize; // Size of received message

            byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer

            for (;;) { // Run forever, accepting and servicing connections
                Socket clntSock = servSock.accept(); // Get client connection

                System.out.println("Handling client at "
                                   + clntSock.getInetAddress().getHostAddress() + " on port "
                                   + clntSock.getPort());

                InputStream in = clntSock.getInputStream();
                OutputStream out = clntSock.getOutputStream();

                // Receive until client closes connection, indicated by -1 return
                while ((recvMsgSize = in.read(byteBuffer)) != -1) {

                    byte[] changeOrder = changeOrder(byteBuffer, recvMsgSize);
                    out.write(changeOrder, 0, recvMsgSize);
                }

                clntSock.close(); // Close the socket. We are done with this client!
            }
        }
        /*
          change order, for example input <code>abc</code> then output <code>cba</code>
         */
        private byte[] changeOrder(byte[] byteBuffer, int recvMsgSize) {
            byte[] result = new byte[recvMsgSize];
            for (int i = 0; i < recvMsgSize; i++) {
                result[i] = byteBuffer[recvMsgSize - 1 - i];
            }
            return result;
        }
    };

   th.start();
}
sina_2831808769
sina_2831808769   Rxr 2015.07.25 14:00
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!
其他相关推荐
请问下面的程序一共输出多少个“-”?
题目:int main(void) {     int i;     for (i = 0; i < 2; i++) {          fork();          printf("-");      }      return 0;  }  A、2 B、4 C、6 D、8 答案:D 解析: fork函数是计算机程序设计中的分叉函数。返回值: 若成功调用一次则返回两个值,
js数组方法考察点详解
来自“阿里巴巴2017秋招前端笔试题”中的一道笔试题:将数组 var a=[1,2,3] 变成数组 [4,3,2,1] 下面的方式正确的是? a.reverse().unshift(4) a.push(4).reverse() a.push(4); a.reverse() a.splice(3,1,4).reverse()
fork()请问下面的程序一共输出多少个“-”?
fork() 题目:请问下面的程序一共输出多少个“-”? #include #include #include int main(void) { int i; for(i=0; i<2; i++){ fork(); printf("-"); } return 0; } 解析:一共输出8个 首先程序一开始
windows下的可执行程序可以再linux下运行吗?
windows下的可执行程序可以再linux下运行吗? 答案:不能 原因有以下: (1) 可执行的二进制文件包含了:机器指令、数据资源、程序运行资源(物理的和虚拟的内存空间、进程、线程资源等)。因此说明了,可执行文件执行之前,操作系统要做一些准备工作,根据不同的操作系统,准备工作是不同的,因此可执行文件的格式是不相同的。Windows下可执行文件格式为PE格式,linux下可执行文件为el
在不修改代码的情况下无限扩展应用项目
在许多需要分模块开发,较为复杂的应用项目(如ERP之类)中,如何做到轻松扩展,往往是一个头疼的问题。 在传统条件下,我们会把各个功能分布在不同的类库中,每添加一个功能就引用一个程序集,而这种方法,我们会发现,当你每添加一个新扩展后,都要对新增的程序集进行引用,这样也意味着,你每次都要重新编译一次主应用程序,这一来一往,维护成本也是有的。 到了.NET 3.5时代,你可能会想到Addin,但这个
unix网络编程1---在linux下运行c程序
之前一直想自学unix网络编程,还特地去买了本史蒂文斯的书。没想到一开始就被那个简单的时间获取客户程序搞晕了。试了N中方式把网上的教程翻了个便都不行。甚至有一段时间故意不去看它。         关键就在unp.h,怎么把它编译成功。 #include "unp.h" //#include "myerr.h" int main(int argc, char **argv
由MFC程序是否能够在Linux上运行谈起
首先,必须面对的现实是,不经修改的mfc程序是不能在linux下运行的,道理很简单,mfc的基石是windowsAPI,而linux上不可能有他。 那么mfc开发的程序就没办法在linux上重用了吗?下面这篇文章为我们提供了一种方法: 将MFC 应用程序移植到Linux 当然,如果你在编写软件的一开始就知道自己的程序需要运行在window和linux下,那么有人会建议你放弃mfc,
MyEclipse代码在Eclipse中运行调试
    之前的项目都在Eclipse中开发,最近接到一个项目是用MyEclipse开发的,上传到SVN上。从代码库中获取发现获取到的代码在Eclipse中无法调试,且点击F3也无法进入代码当中,在网上查了好久,都没有一个系统的解决方案,研究了一下,写此文档作为操作记录。    配置步骤及截图(1)  从SVN上获取代码库中的代码(检出时需选择“作为工作空间中的项目检出”)    工程样式如下:  ...
面试题之final,finally和finalize的区别以及如果catch里面有return语句,请问finally里面的代码还会执行吗?
/*  * 面试题:  * 1:final,finally和finalize的区别  * final:最终的意思,可以修饰类,成员变量,成员方法  *         修饰类,类不能被继承  *         修饰变量,变量是常量  *         修饰方法,方法不能被重写  * finally:是异常处理的一部分,用于释放资源。  *         一般来说,代码肯定会执
多线程程序在多核和单核上运行的不同
1、锁 在单核上,多个线程执行锁或者临界区时,实际上只有一个线程在执行临界区代码,而核心也只支持一个线程执行,因此不存在冲突。如果某个线程持有锁,那只有其他线程不会被调度到CPU上执行,影响的只是持有和释放锁的时间,处理器时刻在运行着。但是在多核上运行时,锁或临界区会导致其余处理器空闲而只允许一个处理器执行持有锁的那个线程,这是一个串行的过程,会影响性能。 2、负载均衡 单核上不用考虑负载均