服务端:
import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;
public class SocketServer {
public static void main(String[] args){
try{
ServerSocket ss = null;
ss = new ServerSocket(4700);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println("Client:"+in.readLine());
String line = din.readLine();
while(!line.equals("bye")){
out.print(line);
System.out.println("Server:"+line);
System.out.println("Client:"+in.readLine());
line = din.readLine();
}
in.close();
out.close();
ss.close();
}catch(IOException e){
System.out.println("文件读取错误");
}
}
}
客户端:
import java.net.Socket;
import java.io.*;
import java.net.ServerSocket;
public class MySocket {
public static void main(String[] args)throws Exception{
Socket s = new Socket("127.0.0.1",4700);
try{
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
String st = din.readLine();
while(!st.equals("bye")){
out.println(st);
out.flush();
System.out.println("Client:"+st);
System.out.println(in.readLine());
st = din.readLine();
}
in.close();
din.close();
s.close();
}catch(IOException e){
return;
}
}
} |
|