用JAVA开发一个简单的聊天软件
服务器端:import java.io.*; import java.net.*; public class TestServer{ public static void main(String args[]){ try{ ServerSocket server = null; try{ server = new ServerSocket(3456); }catch(Exception e){ System.out.println("can not listen to:" + e); } Socket socket = null; try{ socket = server.accept(); }catch(Exception e){ System.out.println("Error:" + e); } String line; BufferedReader is = new BufferedReader(new InputStreamReader( socket.getInputStream())); PrintWriter os = new PrintWriter(socket.getOutputStream()); BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Client:" + is.readLine()); line = sin.readLine(); while (!line.equals("bye")){ os.println(line); os.flush(); System.out.println("Server:" + line); System.out.println("Client:" + is.readLine()); line = sin.readLine(); } is.close(); os.close(); socket.close(); server.close(); }catch(Exception e){ System.out.println("Error" + e); } } } 客户端:import java.io.*; import java.net.*; public class TestClient{ public static void main(String args[]){ try{ Socket socket = new Socket("127.0.0.1",3456); BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); PrintWriter os = new PrintWriter(socket.getOutputStream()); BufferedReader is = new BufferedReader(new InputStreamReader( socket.getInputStream())); String readline; readline = sin.readLine(); while (!readline.equals("bye")){ os.println(readline); os.flush(); System.out.println("Client:" + readline); System.out.println("Server:" + is.readLine()); readline = sin.readLine(); } os.close(); is.close(); socket.close(); }catch(Exception e){ System.out.println("Error" + e); } } } 要么再看看这个 这个应该可以的拉:import java.applet.*; import java.awt.*; import java.io.*; import java.net.*; import java.awt.event.*; public class ChatClient extends Applet{ protected boolean loggedIn;//登入状态 protected Frame cp;//聊天室框架 protected static int PORTNUM=7777; //缺省端口号7777 protected int port;//实际端口号 protected Socket sock; protected BufferedReader is;//用于从sock读取数据的BufferedReader protected PrintWriter pw;//用于向sock写入数据的PrintWriter protected TextField tf;//用于输入的TextField protected TextArea ta;//用于显示对话的TextArea protected Button lib;//登入按钮 protected Button lob;//登出的按钮 final static String TITLE ="Chatroom applet>>>>>>>>>>>>>>>>>>>>>>>>"; protected String paintMessage;//发表的消息 public ChatParameter Chat; public void init(){ paintMessage="正在生成聊天窗口"; repaint(); cp=new Frame(TITLE); cp.setLayout(new BorderLayout()); String portNum=getParameter("port");//呢个参数勿太明 port=PORTNUM; if (portNum!=null) //书上是portNum==null,十分有问题 port=Integer.parseInt(portNum); //CGI ta=new TextArea(14,80); ta.setEditable(false);//read only attribute ta.setFont(new Font("Monospaced",Font.PLAIN,11)); cp.add(BorderLayout.NORTH,ta); Panel p=new Panel(); Button b; //for login button p.add(lib=new Button("Login")); lib.setEnabled(true); lib.requestFocus(); lib.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ login(); lib.setEnabled(false); lob.setEnabled(true); tf.requestFocus();//将键盘输入锁定再右边的文本框中 } }); //for logout button p.add(lob=new Button ("Logout")); lob.setEnabled(false); lob.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ logout(); lib.setEnabled(true); lob.setEnabled(false); lib.requestFocus(); } }); p.add(new Label ("输入消息:")); tf=new TextField(40); tf.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(loggedIn){ //pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野来? int j=tf.getText().indexOf(":"); if(j>0) pw.println(Chat.CMD_MESG+tf.getText()); else pw.println(Chat.CMD_BCAST+tf.getText()); tf.setText("");//勿使用flush()? } } }); p.add(tf); cp.add(BorderLayout.SOUTH,p); cp.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ //如果执行了setVisible或者dispose,关闭窗口 ChatClient.this.cp.setVisible(false); ChatClient.this.cp.dispose(); logout(); } }); cp.pack();//勿明白有咩用? //将Frame cp放在中间 Dimension us=cp.getSize(), them=Toolkit.getDefaultToolkit().getScreenSize(); int newX=(them.width-us.width)/2; int newY=(them.height-us.height)/2; cp.setLocation(newX,newY); cp.setVisible(true); paintMessage="Window should now be visible"; repaint(); } //登录聊天室 public void login(){ if(loggedIn) return; try{ sock=new Socket(getCodeBase().getHost(),port); is=new BufferedReader...
用java做一个两个人之间的聊天软件
客户端import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;public class ChatClient extends Frame { Socket s = null; DataOutputStream dos = null; DataInputStream dis = null; private boolean bConnected = false; TextField tfTxt = new TextField(); TextArea taContent = new TextArea(); Thread tRecv = new Thread(new RecvThread()); public static void main(String[] args) { new ChatClient().launchFrame(); } public void launchFrame() { setLocation(400, 300); this.setSize(300, 300); add(tfTxt, BorderLayout.SOUTH); add(taContent, BorderLayout.NORTH); pack(); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { disconnect(); System.exit(0); } }); tfTxt.addActionListener(new TFListener()); setVisible(true); connect(); tRecv.start(); } public void connect() { try { s = new Socket("127.0.0.1", 8888); dos = new DataOutputStream(s.getOutputStream()); dis = new DataInputStream(s.getInputStream());System.out.println("connected!"); bConnected = true; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void disconnect() { try { dos.close(); dis.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } /* try { bConnected = false; tRecv.join(); } catch(InterruptedException e) { e.printStackTrace(); } finally { try { dos.close(); dis.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } } */ } private class TFListener implements ActionListener { public void actionPerformed(ActionEvent e) { String str = tfTxt.getText().trim(); //taContent.setText(str); tfTxt.setText(""); try {//System.out.println(s); dos.writeUTF(str); dos.flush(); //dos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } private class RecvThread implements Runnable { public void run() { try { while(bConnected) { String str = dis.readUTF(); //System.out.println(str); taContent.setText(taContent.getText() + str + '\n'); } } catch (SocketException e) { System.out.println("退出了,bye!"); } catch (EOFException e) { System.out.println("推出了,bye - bye!"); } catch (IOException e) { e.printStackTrace(); } } }}服务器端import java.io.*;import java.net.*;import java.util.*;public class ChatServer { boolean started = false; ServerSocket ss = null; List clients = new ArrayList(); public static void main(String[] args) { new ChatServer().start(); } public void start() { try { ss = new ServerSocket(8888); started = true; } catch (BindException e) { System.out.println("端口使用中...."); System.out.println("请关掉相关程序并重新运行服务器!"); System.exit(0); } catch (IOException e) { e.printStackTrace(); } try { while(started) { Socket s = ss.accept(); Client c = new Client(s);System.out.println("a client connected!"); new Thread(c).start(); clients.add(c); //dis.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Client implements Runnable { private Socket s; private DataInputStream dis = null; private DataOutputStream dos = null; private boolean bConnected = false; public Client(Socket s) { this.s = s; try { dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); bConnected = true; } catch (IOException e) { e.printStackTrace(); } } public void send(String str) { try { dos.writeUTF(str); } catch (IOException e) { clients.remove(this); System.out.println("对方退出了!我从List里面去掉了!"); //e.printStackTrace(); } } public void run() { try { while(bConnected) { String str = dis.readUTF();System.out.println(str); for(int i=0; i it = clients.iterator(); it.hasNext(); ) { Client c = it.next(); c.send(str); } */ /* Iterator it = clients.iterator(); while(it.hasNext()) { Client c = it.next(); c.send(str); } */ } } catch (EOFException e) { System.out.println("Client closed!"); } catch (IOException e) { e.printStackTrace(); } finally { try { if(dis != null) dis.close(); if(dos != null) dos.close(); if(s != null) { s.close(); //s = null; } } catch (IOException e1) { e1.printStackTrace(); }} } }}
用Java编写一个简单的二人聊天室
这种例子很多的:三个类。
第一个类:package chat;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.net.Socket;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ServerManage extends Thread {//定义线程 private JFrame jFrame; private JTextField enterField; private JTextArea displayArea; private ObjectOutputStream output; private ObjectInputStream input; private Socket connection; //建立GUI public ServerManage(Socket socket){ connection=socket; }//ServerManage private void getStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream() ); output.flush(); input = new ObjectInputStream(connection.getInputStream() ); displayArea.append( "\n客户端已联接!\n" ); } //getStreams private void processConnection() throws IOException //处理联接方法体 { String message = "联接成功,可以会话!";//发消息给CLIENT,通知联接以经建立 output.writeObject( message ); output.flush(); enterField.setEnabled( true ); do { try{ message = ( String ) input.readObject(); displayArea.append( "\n" + message ); displayArea.setCaretPosition(displayArea.getText().length() ); } catch(Exception e){ displayArea.setText("联接关闭....."); } } while ( !message.equals( "客户机: bay" ) );//设定终止口令 } private void closeConnection() throws IOException //关闭联接方法体 { enterField.setEnabled( false ); output.close(); input.close(); connection.close(); }//closeConnection private void sendData( String message ) //发送消息方法 { try { output.writeObject("\n"); output.writeObject( "主机: "+message ); // output.writeObject( message ); output.flush(); displayArea.append( "\n我: "+message ); displayArea.setCaretPosition(displayArea.getText().length() ); // displayArea.append( message ); enterField.setText("");//清除输入行内容 } catch ( IOException ioException ) { displayArea.append( "\n无法识别......" );//异常处理 } } public void run(){ jFrame=new JFrame("与"+ connection.getInetAddress()+"对话"); Container container = jFrame.getContentPane(); enterField = new JTextField();//输入行 enterField.setEnabled(true); enterField.addActionListener(new ActionListener() { public void actionPerformed( ActionEvent event ){ // sendData(enterField.getText());//获取文本框中字符串 sendData(event.getActionCommand()); } } ); //加入事件 displayArea = new JTextArea(10,10);//消息显示区 displayArea.setBackground(Color.lightGray); // displayArea.setForeground (Color.green); Label label=new Label("在下面区域输入要发送的内容,按回车键发送..."); container.add( new JScrollPane( displayArea ),BorderLayout.NORTH ); container.add(label,BorderLayout.CENTER); container.add(enterField, BorderLayout.SOUTH ); jFrame.setSize( 300, 300);//设定窗体大小 jFrame.setVisible( true );//窗体可见 jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); try { while ( true ) { getStreams(); processConnection(); closeConnection(); } } catch ( IOException ioException ) { ioException.printStackTrace(); } } }////////////////第二个类package chat;import java.net.*;import javax.swing.*;public class Server extends JFrame { private static final long serialVersionUID = 1L;private int port=1234;//设定通讯端口为1234 private ServerSocket server; int n=0; public Server(){ try{ server = new ServerSocket( port, 100 );//最多100个对话 while(n<100){ ServerManage serverManage=new ServerManage(server.accept()); serverManage.start(); n++; } } catch(Exception e){ System.out.println(e); } } public static void main( String args[] ) { new Server(); }}////第三个类package chat;//Client.java//导入有关包import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.JOptionPane;import javax.swing.*;public class Client extends JFrame { /** * */ private static final long serialVersionUID = 1L;private JTextField enterField; private JTextArea displayArea; private ObjectOutputStream output; private ObjectInputStream input; private String message =null; private String chatServer; private Socket client;//建立GUI public Client( String host )//以主机IP或主机名为参数 { super( "客户端tip" ); chatServer = host; Container container = getContentPane(); enterField = new JTextField();//输入行 enterField.setEnabled( true ); enterField.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ){ sendData( event.getActionCommand() ); } } );//加入方法(发送消息给主机) displayArea = new JTextArea(10,10);//输出区 Label label=new Label("在下面区...
转载请注明出处51数据库 » 用java写的聊天软件
小陌123