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