问题描述
- 请问下面这个程序,在不改变功能的前提下,可以改装成多线程运行吗?*请贴上代码,谢谢*
-
import java.net.*; // for Socket, ServerSocket, and InetAddress
import java.io.*; // for IOException and Input/OutputStreampublic class Server {
private static final int BUFSIZE = 32; // Size of receive bufferpublic 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