《Java_Socket聊天室完整源代码(10页).doc》由会员分享,可在线阅读,更多相关《Java_Socket聊天室完整源代码(10页).doc(11页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、-说明:本人不才,Java初学者,自己平时也喜欢总结一些东西,然后与大家分享,同时希望得到Java高手的指正和指导,更希望能和广大的Java爱好者交朋友,共同学习Java,分享经验,一起进步。本人QQ:1134135987,非Java爱好者勿加,谢谢!以下代码实现的功能:在一个局域网内,两人在Eclipse的控制台上,可以点对点的进行聊天,并且某一方可以同时输入多句话,以下时实例图片:Server端的示意图:Client端的示意图:实现代码如下:服务端代码:import java.io.*;import .*;public class ServerTest3 public static voi
2、d main(String args) throws Exception / 设置sever端的链接ServerSocket s = new ServerSocket(8888);Socket s1 = s.accept();/ sever等待链接System.out.println(s1.getInetAddress().getHostAddress()+上线了);/ 实例化输出流DataOutputStream dos = new DataOutputStream(s1.getOutputStream();/ 实例化输入流DataInputStream dis = new DataInpu
3、tStream(s1.getInputStream();/ 实例化两个线程的对象Thread msr = new MyServerReader(dis);Thread msw = new MyServerWriter(dos);/ 启动线程msr.start();msw.start();/ 创建一个线程用来进行接收,读取数据class MyServerReader extends Thread private DataInputStream dis;public MyServerReader(DataInputStream dis) this.dis = dis;public void run
4、() String msg;try while (true) msg = dis.readUTF();System.out.println(客户端说: + msg);if (msg.equals(bye) System.out.println(客户端下线,程序退出);System.exit(0); catch (IOException e) System.out.println(e);/ 创建一个进程用来写入并发送数据class MyServerWriter extends Thread private DataOutputStream dos;public MyServerWriter(Da
5、taOutputStream dos) this.dos = dos;public void run() BufferedReader br = new BufferedReader(new InputStreamReader(System.in);String msg;try while (true) msg = br.readLine();dos.writeUTF(msg);if (msg.equals(bye) System.out.println(自己下线,程序退出);System.exit(0); catch (IOException e) System.out.println(e)
6、;客户端代码:import java.io.*;import .*;public class ClientTest3 public static void main(String args) throws Exception, Exception / 链接sever端Socket s1 = new Socket(127.0.0.1, 8888);/ 实例化输入流DataInputStream dis = new DataInputStream(s1.getInputStream();/ 实例化输出流DataOutputStream dos = new DataOutputStream(s1.g
7、etOutputStream();/ 实例化两个进程Thread mcr = new MyClientReader(dis);Thread mcw = new MyClientWriter(dos);/ 启动两个进程mcr.start();mcw.start();/ 创建一个线程用来进行接收读取数据class MyClientReader extends Thread private DataInputStream dis;public MyClientReader(DataInputStream dis) this.dis = dis;public void run() String msg
8、;try while (true) msg = dis.readUTF();System.out.println(服务端说: + msg);if (msg.equals(bye) System.out.println(服务端下线,程序退出);System.exit(0); catch (IOException e) System.out.println(e);/ 创建一个进程用来写入并发送数据class MyClientWriter extends Thread private DataOutputStream dos;public MyClientWriter(DataOutputStrea
9、m dos) this.dos = dos;Overridepublic void run() BufferedReader br = new BufferedReader(new InputStreamReader(System.in);String msg;try while (true) msg = br.readLine();dos.writeUTF(msg);if (msg.equals(bye) System.out.println(自己下线,程序退出);System.exit(0); catch (IOException e) System.out.println(e);第 11 页-