服务端
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket serverSocket;
private Socket socket;
public void getService(){
try {
serverSocket=new ServerSocket(4578);
System.out.println("服务器启动");
} catch (IOException e) {
e.printStackTrace();
}
while(true){
try{
socket=serverSocket.accept();
System.out.println("New connection accepted"
+socket.getInetAddress()+":"
+socket.getPort());
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter=new PrintWriter(socket.getOutputStream(),true);
String msg;
while((msg=bufferedReader.readLine())!=null){
System.out.println(msg);
printWriter.println("echo"+msg);
}
}catch(IOException e){e.printStackTrace();
}finally{
try{
if(socket!=null)
socket.close();
}catch(IOException e){e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException {
new Server().getService();
}
}
客户端
import java.net.*;
import java.io.*;
public class Client {
private String host="localhost";
private int port=4578;
private Socket socket;
public void sendMsg()throws IOException{
socket = new Socket(host,port);
try{
InputStream socketIn=socket.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socketIn));
OutputStream socketOut=socket.getOutputStream();
PrintWriter pw=new PrintWriter(socketOut,true);
BufferedReader localReader=new BufferedReader(new InputStreamReader(System.in));
String msg;
while((msg=localReader.readLine())!=null){
pw.println(msg);
System.out.println(bufferedReader.readLine());
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{socket.close();}catch(IOException e){e.printStackTrace();}
}
}
public static void main(String []args) throws IOException {
new Client().sendMsg();
}
}