import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SocketServer {
private static ExecutorService threadPool = Executors.newFixedThreadPool(5);
//函数入口
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(1234);
while (true){
final Socket socket = server.accept();
threadPool.execute(new Runnable() {
@Override
public void run() {
InputStream inputStream = null;
OutputStream outputStream = null;
String str = "";
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len=inputStream.read(buf))!=-1){
str = new String(buf,0,len);
System.out.println("服务端反转前说: "+str);
char[] char1 = str.toCharArray();
char[] char2 = new char[char1.length];
for (int i=0,j=char2.length-1;i<char1.length;i++,j--){
char2[j]=char1[i];
}
String str1 = new String(char2);
System.out.println("服务端反转后说: "+str1);
outputStream.write(str1.getBytes());
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class SocketClient {
//函数入口
public static void main(String[] args) throws IOException {
//需要服务器的正确的IP地址和端口号
final Socket socket = new Socket("127.0.0.1", 1234);
Scanner scanner = new Scanner(System.in);
OutputStream os= null;
new Thread(new Runnable() {
@Override
public void run() {
// 读Sock里面的数据
InputStream s = null;
try {
s = socket.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = s.read(buf)) != -1) {
System.out.println("收到服务端口反转的语句:" + new String(buf, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
while (true){
os= socket.getOutputStream();
String in="";
in=scanner.next();
os.write((""+in).getBytes());
os.flush();
}
}
}