封装Socket传送类:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class SocketWrapper {
private Socket socket;
private InputStream inputStream;
private BufferedReader inputReader;
private BufferedWriter outputWriter;
public SocketWrapper(Socket socket) throws IOException{
this.socket = socket;
this.inputStream = socket.getInputStream();
this.inputReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
this.outputWriter = new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream(), "UTF-8"));
}
public String readLine() throws IOException{
return this.inputReader.readLine();
}
public void writeLine(String line) throws IOException{
this.outputWriter.write(line + '\n');
this.outputWriter.flush();
}
public void close(){
try{
this.socket.close();
}catch(Exception e){
}
}
}
import java.io.IOException;
import java.net.ServerSocket;
public class SocketServer {
public static void main(String[] args) throws IOException{
ServerSocket serSocket = new ServerSocket(8888);
System.out.println("端口8888已经打开,开始准备接受数据");
SocketWrapper socket = null;
try{
socket = new SocketWrapper(serSocket.accept());
String line = socket.readLine();
while(!"bye".equals(line)){
System.out.println("客户端传来数据:" + line);
socket.writeLine("我接收到你的数据:" + line);
line = socket.readLine();
}
socket.writeLine("close");
}finally{
if(socket != null)socket.close();
}
}
}
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class SocketClient {
public static void main(String[] args) throws IOException{
Scanner scanner = new Scanner(System.in);
SocketWrapper socket = new SocketWrapper(
new Socket("localhost", 8888));
try{
System.out.println("已经连接上服务器,现在可以输入数据开始通信了");
String sendMsg = scanner.nextLine();
socket.writeLine(sendMsg);
String recivedMsg = socket.readLine();
while(!"close".equals(recivedMsg)){
System.out.println("===[服务器返回]===>" + recivedMsg);
sendMsg = scanner.nextLine();
socket.writeLine(sendMsg);
recivedMsg = socket.readLine();
}
System.out.println("我是客户端,结束了!");
}finally{
if(socket != null)socket.close();
}
}
}