深网 2015-07-08 16:50 采纳率: 100%
浏览 2076
已采纳

Socket编程初级问题,关于消息发送

本人刚接触java以及socket编程,入门级水平。
现已知客户端跟服务端java代码如下:

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

public class TCP_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)

/*
(添加代码,企图改变字符串顺序)

*/

   out.write(byteBuffer, 0, recvMsgSize);




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

}
}


//客户端
import java.net.*; // for Socket
import java.io.*; // for IOException and Input/OutputStream

public class TCPEchoClient {

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

if ((args.length < 2) || (args.length > 3))  // Test for correct # of args
  throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]");

String server = args[0];       // Server name or IP address
// Convert input String to bytes using the default character encoding
byte[] byteBuffer = args[1].getBytes();

int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;

// Create socket that is connected to server on specified port
Socket 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

}
}


一般情况下,是开两个终端分别运行服务端与客户端,
先执行服务端,显示如下:
g136@ispc29Lx:~$ java TCP_Server 50000

再执行客户端,依次输入IP 字符串 port号,显示如下
g136@ispc29Lx:~$ java TCPEchoClient 150.86.64.169 ab 50000

然后客户端跟服务端都会产生反应,如下:
g136@ispc29Lx:~$ java TCP_Server 50000
Handling client at 150.86.64.169 on port 58002

g136@ispc29Lx:~$ java TCPEchoClient 150.86.64.169 ab 50000
Connected to server...sending echo string
Received: ab

输入的是ab,服务端原封不动的返回的也是ab,我希望能在服务端添加一段代码,使返回的字符顺序改变成ba;或者把ab变成大写,怎么都行,只是希望能对原字符串进行改变。
第一次提问题,还请多多包涵。

  • 写回答

10条回答 默认 最新

  • JonsonJiao 2015-07-09 02:46
    关注

    直接贴代码吧,修改了服务端的代码,客户端没有修改。主要修改的是服务端增加一个字符串顺序逆序的方法。
    你的代码很好了,没有什么问题,很棒的是全部英文,另外粘贴到Eclipse中没有警告和错误,很棒。

    package com.test.jvm;
    
    //服务端
    import java.net.*; // for Socket, ServerSocket, and InetAddress
    import java.io.*; // for IOException and Input/OutputStream
    
    public class TCP_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>
         * 
         * @param byteBuffer
         *            receive bytes
         * @param recvMsgSize
         *            valid length of the receive bytes, cannot larger than
         *            byteBuffer's length.
         * @return
         */
        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;
        }
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器