单线程。
SERVER端
1 import java.io.IOException; 2 import java.net.*; 3 import java.io.*; 4 public class Chatserver { 5 6 7 8 public static void main(String[] args) { 9 boolean started=false; 10 ServerSocket ss=null;//初始化 11 Socket s=null; 12 DataInputStream dis=null; 13 try { 14 ss=new ServerSocket(8888);//端口号8888,TCP 15 }catch (BindException e){ 16 System.out.println("端口使用中"); 17 System.exit(0); 18 }catch(IOException e){ 19 e.printStackTrace();//给出方法的调用程序,一直到异常的产生位置 20 } 21 try{ 22 started=true;//连接上 23 while(started) 24 { 25 boolean bConnected=false; 26 s=ss.accept(); 27 System.out.println("a client connected!"); 28 bConnected=true;//接收到对方之后变成true 29 dis=new DataInputStream(s.getInputStream()); 30 while(bConnected){//有东西来就读 31 String str=dis.readUTF();//阻塞式 32 System.out.println(str); 33 } 34 //dis.close(); 35 } 36 }catch (EOFException e){ 37 System.out.println("Client closed!"); 38 } 39 catch (IOException e) { 40 e.printStackTrace(); 41 }finally{ 42 try{ 43 if(dis !=null) dis.close(); 44 if(s !=null) s.close(); 45 }catch(IOException e1){ 46 e1.printStackTrace(); 47 } 48 } 49 50 } 51 52 }
客户端
1 import java.awt.*; 2 import java.awt.event.*; 3 import java.io.IOException; 4 import java.net.*; 5 import java.io.*; 6 public class Chatclient extends Frame{ 7 8 Socket s=null; 9 DataOutputStream dos=null; 10 11 TextField tfTxt=new TextField();//只有一行可以写,有一个ACTION 12 TextArea taContent=new TextArea();//标签定义多行的文本输入控件 13 14 15 public static void main(String[] args) { 16 new Chatclient().LaunchFrame(); 17 } 18 19 public void LaunchFrame() 20 { 21 setLocation(400,300); 22 this.setSize(300,300); 23 add(tfTxt,BorderLayout.SOUTH); 24 add(taContent,BorderLayout.NORTH); 25 pack(); 26 this.addWindowListener(new WindowAdapter(){//关闭窗口 27 28 @Override 29 public void windowClosing(WindowEvent e) { 30 disconnect(); 31 System.exit(0); 32 } 33 34 });//匿名类 35 tfTxt.addActionListener(new TFListener()); 36 setVisible(true); 37 connect(); 38 } 39 40 public void connect() 41 { 42 try { 43 s=new Socket("127.0.0.1",8888); 44 dos=new DataOutputStream(s.getOutputStream()); 45 System.out.println("connected!"); 46 } catch (UnknownHostException e) { 47 e.printStackTrace(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 52 } 53 54 public void disconnect()//关闭方法 55 { 56 try{ 57 dos.close(); 58 s.close(); 59 }catch (IOException e){ 60 e.printStackTrace(); 61 } 62 63 64 } 65 private class TFListener implements ActionListener 66 { 67 public void actionPerformed(ActionEvent e) {//一敲回车 68 String str=tfTxt.getText().trim(); 69 taContent.setText(str); 70 tfTxt.setText("");//回车之后清空 71 try { 72 //DataOutputStream dos=new DataOutputStream(s.getOutputStream()); 73 dos.writeUTF(str);//把stream输出去 74 dos.flush(); 75 //dos.close(); 76 } catch (IOException e1) { 77 e1.printStackTrace(); 78 } 79 80 81 } 82 83 }//内部类 84 }