java简单聊天程序代码 java简单聊天程序代码辩答PPT( 三 )


} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void disconnect(){
try {
dos.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new MainChat().chatLaunch();
}
}
服务方:
package com.king.Char;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
public static void main(String[] args) {
boolean statred = false;
try {
ServerSocket ss = new ServerSocket(8888);
statred = true;
while (statred) {
boolean bConnection = false;
Socket s = ss.accept();
bConnection = true;
DataInputStream dis = new DataInputStream(s.getInputStream());
while (bConnection) {
//.readUTF()会阻塞 一直等待接收数据使用线程解决
String str = dis.readUTF();
}
dis.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//不用为类服务 写内部类即可
class myThreadimplements Runnable{
//每个客户端有自己的相关信心
private Socket s;
private DataInputStream dis=null;
public void run(){
}
}
}
如何用java做一个聊天小程序 要求使用图形用户界面,可以实现一个聊天室中多人聊天,也可以两人私聊,给你一个简单的实现吧,注意一定要先运行MyServer.java
//MyCilent.java
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyClient extends JFrame implements ActionListener{
JTextField tf;
JTextArea tx;
JButton bt;
PrintWriter out;
public MyClient(){
tf=new JTextField(20);
tx=new JTextArea();
tx.setLineWrap(true);
tx.setWrapStyleWord(true);
JPanel pan=new JPanel();
JScrollPane jsp=new JScrollPane(tx);
add(jsp,"Center");
bt=new JButton("SEND");
bt.addActionListener(this);
pan.add(tf);
pan.add(bt);
add(pan,"South");
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setTitle("THE CLIENT");
setSize(400,300);
setVisible(true);
try{
Socket socket=new Socket("127.0.0.1",1680);
out=new PrintWriter(socket.getOutputStream(),true);
InputStreamReader in = new InputStreamReader(socket.getInputStream());
BufferedReader sin=new BufferedReader(in);
String s;
while(true){
s=sin.readLine();
tx.append("#Server Said#:"+s+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bt){
tx.append("@Client Said@: "+tf.getText()+"\n");
out.println(tf.getText());
tf.setText("");
}
}
public static void main(String[] args){
MyClient mct = new MyClient();
}
}
//MyServer.java
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyServer extends JFrame implements ActionListener{
JTextField tf;
JTextArea tx;
JButton bt;
JScrollPane jsp;
JPanel pan;
PrintWriter out;
public MyServer(){
tx=new JTextArea();
tx.setLineWrap(true);
tx.setWrapStyleWord(true);
jsp=new JScrollPane(tx);

推荐阅读