Java基于Tcp的基础聊天功能实例
程序员文章站
2022-04-18 09:44:35
本文实例讲述了java基于tcp的基础聊天功能。分享给大家供大家参考,具体如下:
最基础的聊天,用户端和服务器端每次说一句,而且严格规定了先后到顺序。
服务器端:
imp...
本文实例讲述了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个个数据流和端口。