本人刚接触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;
}
}
如果你的发送与接收功能都没有错,只能说你对字符串操作,即反转的功能实现有问题。
这个你接收到字符串后,既然还原出来发送数据了,你自己想再转换,就对byte数组进行对应转换就可以了。基本就是字符数组操作
试试String类的public StringBuffer reverse()方法
或者自编写代码,如下:
public static String reverse(String str){
return new StringBuilder(str).reverse().toString();
}
这个消息的接收传递应该是没问题的,看看是不是字符串的处理上有什么问题
首先要把你读取到的内容转换成字符串再进行字符串的其他操作就好了
输入的是ab,服务端原封不动的返回的也是ab,我希望能在服务端添加一段代码,使返回的字符顺序改变成ba;或者把ab变成大写,怎么都行,只是希望能对原字符串进行改变。
服务器端接收到字符串,进行相应处理呗,通讯都调顺了,处理字符串有神马难度呢?
服务器接收到数据之后的字符串处理
就是byteBuffer里面的字符
首先假设楼主知道服务端代码中的那个for循环是做什么用的。
楼主的问题是如何将服务端接收的内容进行处理,倒序,大写之类的。首先应该拿到这个接收到的字符串吧。
服务端的代码是在for循环中使用输入流读取字节的方式拿到的,每都一个字节数组就写到客户端去了。楼主只要在while循环中把所有字节都收集到,转换成字符串,然后对字符串做出相应处理即可。
可以使用ByteArrayOutputStream baos = new ByteArrayOutputStream(); 来收集字节,baos.write(byteBuffer, 0, recvMsgSize);
经过循环写到baos里面,写完之后,byte[] bytes = baos.toByteArray();这样就得到了服务端发过来的内容的所有字节。然后把这个字节数组转换成String message = new String(bytes); 拿到message后,你就可以做自己的处理了。
处理完后,还要把处理之后得到的字符串转成成字节数组发到客户端去。比如message经过处理之后是tempMessage,那么byte[] tempBytes = tempMessage.getBytes();就得到了字符串转成字节数组,再通过服务端的 out.write(tempBytes, 0, tempBytes.length);一下写到客户端。
搞定,能解决楼主的问题吗?
呃......你这个问题已经不是socket编程初级问题了,而是java编程初级问题.你的socket服务端与服务端已经能正常通讯了.并且能拿到客户端发过来的字符串了.如何操作这个字符串,就看你的心情了.
例如,你现在可以直接在服务端写死,让它返回"AB". out.write("AB", 0, 2); //2是AB的长度
看到了吧,你服务端想返回什么东西,是可以随便写的.而不是只能输出它接收到的东西.