标签:
//客户端程序1:ChatClient.java<pre name="code" class="java">import java.io.*; import java.net.*; import java.applet.Applet; public class ChatServer { public static void main(String[]args){ try{ ServerSocket server = null; try{ server = new ServerSocket(4000); System.out.println("准备好了。退出输入bye"); }catch(Exception e){ System.out.println("can not listen to" + e); } Socket socket = null; try{ socket = server.accept(); }catch(Exception e){ System.out.println("Error." + e); } String line; BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter os = new PrintWriter(socket.getOutputStream()); BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Client:" + is.readLine()); line = sin.readLine(); while(! line.equals("bye")){ os.println(line); os.flush(); System.out.println("Server:" + line); System.out.println("Client:" + is.readLine()); line = sin.readLine(); } os.close(); is.close(); socket.close(); server.close(); }catch(Exception e){ System.out.println("Error:" + e); } } }//客户端程序2:ChatServer.java
import java.io.*; import java.net.*; public class CgatClient { public static void main(String[]args){ try{ Socket socket = new Socket("127.0.0.1",4000); System.out.println("输入你要说的话,如果要退出输入bye"); BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); PrintWriter os = new PrintWriter(socket.getOutputStream()); BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); String readline; readline = sin.readLine(); while(! readline.equals("bye")){ os.println(readline); os.flush(); System.out.println("CatClient:"+ readline); System.out.println("Server:" + is.readLine()); readline = sin.readLine(); } os.close(); is.close(); socket.close(); }catch(Exception e){ System.out.println("Error" + e); } } }
//实现结果就是无论在那个程序所编译出来的对话框,你在里面输入你要说的话,就会在另外一个对话框显示出来。此两个小程序实现的是简单对话交流。
//该对话框的结束时输入bye,即会话结束。
标签:
原文地址:http://blog.csdn.net/u014005594/article/details/45951091