华北电力大学教学用ppt-10-网络编程精选.ppt
文本预览下载声明
public void actionPerformed(ActionEvent e) { try { String str=tf.getText( ); byte[ ] buf=str.getBytes( ); tf.setText(null); out.write(buf);//发送服务器说的话 ta.append(我说:+str); ta.append(\n); } catch(IOException ioe) { } } public static void main(String args[ ]) { new chatServer( ); } } import java.io.*; import java.awt.*; import java.awt.event.*; import .*; public class chatClient extends Frame implements ActionListener { Label label=new Label(聊天); Panel panel=new Panel( ); TextField tf=new TextField(10); TextArea ta=new TextArea( ); Socket client; InputStream in; OutputStream out; 客户端: 基于Socket 的聊天程序 public chatClient( )//构造方法 { super(客户机); setSize(250,250); panel.add(label); panel.add(tf); tf.addActionListener(this); add(North,panel); add(Center,ta); addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent e) { System.exit(0);}} ); show( ); try { client= new Socket(InetAddress.getLocalHost( ),5000); ta.append(已连接到服务器:+ client.getInetAddress( ).getHostName( )+\n\n); in=client.getInputStream( ); out=client.getOutputStream( ); } catch(IOException ioe) { } while(true)//接受服务器端说的话 { try { byte[ ] buf=new byte[256]; in.read(buf); String str=new String(buf); ta.append(服务器说:+str); ta.append(\n); } catch(IOException e) { } } } public void actionPerformed(ActionEvent e) { try { String str=tf.getText( ); byte[ ] buf=str.getBytes( ); tf.setText(null); out.write(buf); ta.append(我说:+str); ta.append(\n); } ca
显示全部