lisliefor
发贴: 287
积分: 7
|
于 2006-06-01 11:11
把你的程序小改动了一下! 传递中文,外面套一个过滤流嘛!中途转ISO8859-1,UTF-8,UTF-16编码。 Tcpserver.java
package help;
import java.io.*; import java.net.*;
public class Tcpserver { public static void main(String[] args) throws IOException { ServerSocket svrsoc = null; Socket soc = null; BufferedReader in = null; PrintStream out = null; boolean Flag = true; try { svrsoc = new ServerSocket(5554); System.out.println("Server start...."); soc = svrsoc.accept();
in = new BufferedReader(new InputStreamReader(soc.getInputStream())); out = new PrintStream(soc.getOutputStream()); while(Flag){ String s = in.readLine(); System.out.println("Server gets Message:"+s); if(s.equals("1")){ out.println("我"); out.flush(); } else if(s.equals("2")){ out.println("是"); out.flush(); } else if(s.equals("3")){ out.println("猪猪"); out.flush(); } else if(s.equals("exit")) Flag = false; } } catch (Exception e) { System.out.println("error:" + e); } finally { in.close(); out.close(); soc.close(); svrsoc.close(); System.exit(0); } } }
Tcpclient.java
package help;
import java.io.*; import java.net.*;
public class Tcpclient { public static void main(String[] args) throws IOException { Socket soc = null; BufferedReader in = null; PrintStream out = null; BufferedReader sysin = null; String strout = null; boolean Flag = true; try { soc = new Socket("127.0.0.1", 5554); System.out.println("Connecting to the Server"); in = new BufferedReader(new InputStreamReader(soc.getInputStream())); out = new PrintStream(soc.getOutputStream()); while(Flag){ sysin = new BufferedReader(new InputStreamReader(System.in)); strout = sysin.readLine(); out.println(strout); out.flush(); System.out.println("Client send:"+strout); if(strout.equals("exit")) Flag = false; String s = in.readLine(); System.out.println("Server said:"+s); } } catch (Exception e) { System.out.println("error:" + e); } finally { in.close(); out.close(); sysin.close(); soc.close(); System.exit(0); } } }
|