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

问题描述

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

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;
}

}

解决方案

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

服务端改成:


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();
        }
    }

}

解决方案二:

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();
    }

解决方案三:

你想要的例子
http://lupingzi.iteye.com/blog/509177

解决方案四:

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();
}

解决方案五:

http://lupingzi.iteye.com/blog/509177

时间: 2025-01-30 18:10:20

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

在不改变语言的前提下如何推进Java的不断演进

James Gosling在"The Feel of Java"中说到: Java是一种蓝领语言,它并非博士的论文素材而是用于完成工作的语言.各式各样的程序员都非常熟 悉Java,因为在设计Java之初我就坚持这样一种观点:选择久经考验的东西而非仅仅是听起来很美. Java所获得的巨大成功证明了这种设计方式是正确的,但如果这依然是当今Java的重要目标的话,那 么其结果就是语言的演进将变得非常缓慢.除此以外,Java是一门成熟.使用广泛的语言这个事实也将导 致其演进过程充满了困难.一方

怎么将只能在32bit下运行的程序在64bit下虚拟成32bit运行,请大牛给些意见!

问题描述 现在我有个程序,但是只能在32bit下的系统运行,64bit的运行不了,因为现在客户的电脑很多都是win764bit的,所以老板想要在64bit下也能运行,是不是能在64bit下虚拟成32bit的运行,怎么实现呢?大牛能给个指导意见吗? 解决方案 解决方案二:估计就是你的程序是AnyCPU方式编译的,改成x86方式编译应该就可以了解决方案三:这些都尝试过了,都不行的!因为这个程序是破解的,所以按常规的方法没那么简单就会弄好的!解决方案四:既然破解有问题,那么重新破解呗.解决方案五:他只

java jlabel-想实现从数据库读出数据到label的功能,但老是在jLabel那里出问题,请大家帮忙看看吧~谢谢~

问题描述 想实现从数据库读出数据到label的功能,但老是在jLabel那里出问题,请大家帮忙看看吧~谢谢~ public class Operate_Stu extends javax.swing.JFrame { public static String public_must="123"; public static String public_select="0"; public static String major_must="0";

服务器-java socket 在外网和内网传输问题

问题描述 java socket 在外网和内网传输问题 今天写了一个java Socket的客户端和服务器端程序,在局域网环境中,客户端和服务端能够互相发送数据. 后来想把服务端的ip用Nat123映射出去,用客户端连接服务端映射出来的域名和端口结果服务端能接收客户端的数据,但客户端接收不了服务端的数据,本人百思不得其解,想请高手帮忙解答,本人感激不尽. 解决方案 楼主,我以前也和你做过同样的东西.当时我还研究了nat打洞.然而到最后我花了8块钱注册一个花生壳的内网版,结果就成了.而且其实自己映

java socket通信,字节丢失问题

问题描述 java socket通信,字节丢失问题 请教高手一个问题: 我现在在多台win7和xp的主机上进行java的socket通信,主机间的源代码是通过svn同步,肯定完全一样,现在问题是(以下测试的socket通信文件完全一样):两台xp主机间通信完全没有问题,xp往win7发送也没有问题 问题出在:当win7往xp发送数据时,就会丢字节,在xp上最多接收8755个字节(接收缓冲区足够大),这样该如何解决,有没有哪位也碰到过同样的问题?麻烦指点下... 解决方案 是必现的吗......?

java socket绑定 255 广播地址异常

问题描述 java socket绑定 255 广播地址异常 绑定192.168.0.255时出现异常,改成127.0.0.1时可以正常运行,不知道为什么 public class Tel implements Runnable{ public static void main(String[] args) { Tel tel = new Tel(); new Thread(tel).start(); try { Socket socket = new Socket("192.168.0.255&

link环境下,用codefirst制作网盘软件,请问如何实现无限文件夹的功能

问题描述 link环境下,用codefirst制作网盘软件,请问如何实现无限文件夹的功能 link环境下,用codefirst制作网盘软件,请问如何实现无限文件夹的功能 解决方案 http://www.jb51.net/article/20039.htm

java socket多线程的时间问题

问题描述 java socket多线程的时间问题 各位大神你们好, 我正在用java写一个接收服务器数据并进行统计的程序, 我用的是多线程socket. 该程序要求能够每秒钟接收几千条数据, 数据中包含value和timestamp以及其他字段. 每个数据通过单独的连接发送, 接收之后统计每秒的钟数据的最大值与平均值(指的是数据中所含有的"value"字段的值), 并将其存储到本地. 但是使用多线程时我有个疑问, 就是怎么判断是否到了1秒. 如果使用本地时钟计算肯定会与服务器有出入,

编程-java菜鸟程序员提问:求大神给我说说线程在什么场景下用,以及多线程工作原理。谢谢

问题描述 java菜鸟程序员提问:求大神给我说说线程在什么场景下用,以及多线程工作原理.谢谢 现在java线程编程应用广泛吗?哪些时候适合或必须要用多多线程编程呢?多线程的工作原理是怎样的呢?求大神们指导指导,谢了! 解决方案 (1)线程的工作场景主要有两条: 一个是并发操作,避免阻塞和更有效利用资源.典型的例子有:在长时间工作的程序中使用工作线程避免界面失去响应.在网络下载程序中,使用多个线程提高对网络的使用效率,更快下载文件. 一个是并行,线程是处理器调度的最小单位.如果你的计算机配置了多个