程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> socket-Socket編程初級問題,關於消息發送

socket-Socket編程初級問題,關於消息發送

編輯:編程綜合問答
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變成大寫,怎麼都行,只是希望能對原字符串進行改變。
第一次提問題,還請多多包涵。

最佳回答:


直接貼代碼吧,修改了服務端的代碼,客戶端沒有修改。主要修改的是服務端增加一個字符串順序逆序的方法。
你的代碼很好了,沒有什麼問題,很棒的是全部英文,另外粘貼到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;
    }
} 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved