Java基于Tcp的基础聊天功能实例
人气:0本文实例讲述了Java基于Tcp的基础聊天功能。分享给大家供大家参考,具体如下:
最基础的聊天,用户端和服务器端每次说一句,而且严格规定了先后到顺序。
服务器端:
import java.io.*; import java.net.*; public class ChatServer { public static void main(String[] args) { ServerSocket server = null; try { server = new ServerSocket(12138); } catch (IOException e) { System.out.println("error" + e); } // server = null; try { Socket ac = null; // ac = new Socket(); // ac = null; ac = server.accept(); BufferedReader is = null; is = new BufferedReader(new InputStreamReader(ac.getInputStream())); BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); PrintWriter os = new PrintWriter(ac.getOutputStream()); String line = null; System.out.println("clinent " + is.readLine()); line = dis.readLine(); while(!line.equals("bey")) { os.println(line); os.flush(); System.out.println("server " + line); System.out.println("client " + is.readLine()); line = dis.readLine(); } os.close(); dis.close(); is.close(); ac.close(); } catch (Exception e) { System.out.println("error" + e); } } }
用户端:
public class ChatClient { public static void main(String[] args) { Socket client = null; try { client = new Socket("127.0.0.1",12138); BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter os = new PrintWriter(client.getOutputStream()); String line = dis.readLine(); while(!line.equals("bey")) { os.println(line); os.flush(); System.out.println("client " + line); System.out.println("server " + is.readLine()); line = is.readLine(); } os.close(); dis.close(); is.close(); client.close(); } catch (Exception e) { System.out.println("error" + e); } } }
无论是用户端还是服务器端都用了BufferedReader用来写入一些了连续的字符串,用PrintWriter进行输出。
注:BufferedWriter接收到的参数需要是字符类的数据流,所以要建一个inputStreamReader,而InputStreamReader的参数是数据流即可。
上面规定了写入的顺序是客户端先写,然后是服务器端;
注意要在循环结束的时候close个个数据流和端口。
希望本文所述对大家java程序设计有所帮助。
您可能感兴趣的文章:
加载全部内容