本文为大家分享了java实现简单聊天软件的具体代码,供大家参考,具体内容如下
介绍
这是我自己学习Socket时写的,用到了多线程,Socket的知识,还有Java的IO技术,并且做了一个Java的UI,废话不多说,先上效果图
SendThread
这个类是用来实现数据的发送的,当按键按下时,会调用sendMessage方法
public class SendThread { ChatWindow chatWindow; private String remoteIP = ""; private int port = 0; private String message = ""; public SendThread(int port,ChatWindow window) { chatWindow = window; } public void notRun() { InetSocketAddress isa = new InetSocketAddress(remoteIP, port); try { Socket socket = new Socket(); socket.connect(isa); OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream()); writer.write(message); writer.flush(); writer.close(); System.out.println("将数据写入到流中"); } catch (IOException e) { e.printStackTrace(); }finally{ message = ""; } } public void senMessage(String host,int port,String message){ remoteIP = host; this.port = port; this.message = message; notRun(); } }