Write an online chat java applet hope to help novice
http://www.pudn.com/downloads198/sourcecode/java/jsp/detail930598.htmlhttp://download.csdn.net/source/1648133
java小程序,小游戏扫雷,俄罗斯方块,在线聊天,五子棋等
http://www.pudn.com/downloads198/sourcecode/java/jsp/detail930598.htmlhttp://download.csdn.net/source/1648133
java小程序,小游戏扫雷,俄罗斯方块,在线聊天,五子棋等
网上挺多的吧。找找。不过还是建议你把思路想想自己动手做做。
import java.net.*;
import java.io.*;
import java.util.*; public class ChatServer {
public static void main(String[] args) throws Exception {
ServerSocket ss=new ServerSocket(8080);
List list=new ArrayList();
while(true){
Socket s=ss.accept();
list.add(s);
Thread t=new ServerThread(s,list);
t.start();
}
}
}
class ServerThread extends Thread{
Socket s;
List list;
BufferedReader in;
PrintWriter out;
public ServerThread(Socket s, List list){
this.s = s;
this.list = list;
try {
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(s.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
while(true){
try {
String str=in.readLine(); if (str==null) return;
Iterator it=list.iterator();
while(it.hasNext()){
Socket socket=(Socket)(it.next());
PrintWriter o=new PrintWriter(socket.getOutputStream());
o.println(str);
o.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
return;
}
}
}
}
import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import java.awt.event.*;public class ChatClient{
public static void main(String[] args){
ChatClient cc=new ChatClient();
cc.receive();
}
JTextField jtf;
JTextArea jta;
Socket s;
PrintWriter out;
BufferedReader in;
public ChatClient(){
JFrame frame=new JFrame("ChatClient");
frame.setSize(400,300);
jta=new JTextArea();
jta.setEditable(false);
jtf=new JTextField();
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
send();
}
});
frame.getContentPane().add(new JScrollPane(jta));
frame.getContentPane().add(jtf,"South");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); try {
s=new Socket("localhost",8080);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(s.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void receive(){
while(true){
try {
String text=in.readLine();
Date d = new Date();
String tm = "";
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm:ss a MM.dd");
tm = sdf.format(d);
this.jta.append(text + "\t[Time:" + tm + "]\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
public void send(){
String text=this.jtf.getText();
String text1=System.getProperty("user.name");
this.jtf.setText("");
out.println(text1 + ": " + text);
out.flush();
}
}