服务器端代码:
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.net.ServerSocket; 4 import java.net.Socket; 5 6 public class Server { 7 public static void main(String[] args) { 8 ServerSocket server; 9 try{10 server = new ServerSocket(1111);11 Socket socket = server.accept();12 13 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));14 System.out.println(br.readLine());15 br.close();16 socket.close();17 server.close();18 }catch (Exception e) {19 System.out.println(e);20 }21 }22 }
客户端代码:
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.io.PrintStream; 4 import java.net.Socket; 5 6 public class Client { 7 public static void main(String[] args) { 8 Socket socket; 9 PrintStream ps;10 try {11 socket = new Socket("127.0.0.1",1111);12 System.out.println("connect successfully...");13 System.out.println("Please input some WORDS to server:");14 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));15 String content = null;16 try {17 content = br.readLine();18 } catch (Exception e) {19 20 }21 ps = new PrintStream(socket.getOutputStream(),true,"UTF-8");22 ps.print(content);23 24 socket.close();25 } catch (Exception e) {26 System.out.println(e);27 }28 }29 }
测试发现目前还是存在乱码问题。比如传过去的中文标点符号不能正确的显示...