以下是ChatServer程序:
package TCPChat;import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;public class ChatServer extends Thread{ static TextArea ta;
static TextField tfWord;
ServerSocket ss;
public static void main(String[] args) {

// 界面
Frame f=new Frame("服务端");
 /*TextField tfIP=new TextField(15);
 TextField tfPort=new TextField(6);*/
  ta=new TextArea(20,50);
 tfWord=new TextField(45);
 Panel pN=new Panel();
 Panel pC=new Panel();
 Panel pS=new Panel();
 BorderLayout bl=new BorderLayout();
 /*pN.add(tfIP);
 pN.add(tfPort);*/
 pC.add(ta);
 pS.add(tfWord);
// f.add(pN,bl.NORTH);
 f.add(pC,bl.CENTER);
 f.add(pS,bl.SOUTH);
 
 f.setSize(500, 500);
 f.setLocation(50, 200);
 f.setVisible(true);
 f.pack();
 //退出命令响应
 f.addWindowListener(new WindowAdapter()
 {
 public void windowClosing(WindowEvent e)  
 {
 System.exit(0);
 }
 });
 new Thread(new ChatServer()).start();//启动接收线程
 //添加发送响应
 tfWord.addKeyListener(new KeyAdapter()
 {

 public void keyReleased(KeyEvent e)  
 {

 if(e.getKeyCode()==e.VK_ENTER)
 {


try {
//发送
 String strsend=new String(tfWord.getText()+"\n");//储备数据
 Socket s=new Socket(InetAddress.getByName("127.0.0.1"),9009);
 OutputStream os=s.getOutputStream();
 DataOutputStream dos=new DataOutputStream(os);
 dos.writeUTF(strsend+"\n");

} catch (Exception e1) {
e1.printStackTrace();
}

 }
}
   
 
 });
}
//接收线程
public void run()
{
try {
 //接收客户端
ss=new ServerSocket(9009);
Socket s=ss.accept();
//创建接收流
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
String str=dis.readUTF();//接收数据并存入str
//显示数据
ta.append(str+"\n");//显示在TextArea中

} catch (IOException e) {
e.printStackTrace();
}


}}
**************************
以下是ChatClient程序:
package TCPChat;import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;public class ChatClient extends Thread{
static TextArea ta;
static TextField tfWord;
Socket s;
public static void main(String[] args) {
// 界面
Frame f=new Frame("客户端");
 /*TextField tfIP=new TextField(15);
 TextField tfPort=new TextField(6);*/
  ta=new TextArea(20,50);
 tfWord=new TextField(45);
 Panel pN=new Panel();
 Panel pC=new Panel();
 Panel pS=new Panel();
 BorderLayout bl=new BorderLayout();
 /*pN.add(tfIP);
 pN.add(tfPort);*/
 pC.add(ta);
 pS.add(tfWord);
// f.add(pN,bl.NORTH);
 f.add(pC,bl.CENTER);
 f.add(pS,bl.SOUTH);
 
 f.setSize(500, 500);
 f.setLocation(500, 200);
 f.setVisible(true);
 f.pack();
 //退出命令响应
 f.addWindowListener(new WindowAdapter()
 {
 public void windowClosing(WindowEvent e)  
 {
 System.exit(0);
 } });  
// 启动发送线程
new Thread(new ChatClient()).start();
//接收响应
tfWord.addKeyListener(new KeyAdapter()
 {

 public void keyReleased(KeyEvent e)  
 {

 if(e.getKeyCode()==e.VK_ENTER)
 {


try {

 Socket s=new Socket(InetAddress.getByName("127.0.0.1"),9009);
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
String str=dis.readUTF();//接收数据并存入str
//显示
ta.append(str+"\n");

} catch (Exception e1) {
e1.printStackTrace();
}

 }
}
   
 
 });

}

//发送线程
public void run()
{
/*String strsend=new String(tfWord.getText()+"\n");//储备数据 try {
Socket s=new Socket(InetAddress.getByName("127.0.0.1"),9009);
OutputStream os = s.getOutputStream();
 DataOutputStream dos=new DataOutputStream(os);
 dos.writeUTF(strsend+"\n");

} catch (IOException e) {
e.printStackTrace();
}*/
tfWord.addKeyListener(new KeyAdapter()
 {

 public void keyReleased(KeyEvent e)  
 {

 if(e.getKeyCode()==e.VK_ENTER)
 {


try {
//发送
 String strsend=new String(tfWord.getText()+"\n");//储备数据
 Socket s=new Socket(InetAddress.getByName("127.0.0.1"),9009);
 OutputStream os=s.getOutputStream();
 DataOutputStream dos=new DataOutputStream(os);
 dos.writeUTF(strsend+"\n");
dos.close();
s.close();
} catch (Exception e1) {
e1.printStackTrace();
}

 }
}
   
 
 });

}
}

解决方案 »

  1.   

    简单的通信程序,自己编写就可以了。
    我楼主的代码是关于聊天的,那么传输的数据应该是字符串。
    推荐使用BufferedReader和BufferedWriter两个类来做处理,当然在发送的时候,要注意flush和写入换行符。
    使用DataOutputStream 之类的,会使程序复杂化。
      

  2.   

    运行的时候怎么运行啊?ChatServer程序编译通过了,执行错误啊
      

  3.   

    package com.tianlesoftware.basejava;
    import java.io.*;
    import java.net.*;
    import java.util.*;public class ChatServer {
    boolean started = false;
    ServerSocket ss = null;

    List<Client> clients = new ArrayList<Client>();

    public static void main(String[] args) {
    new ChatServer().start();
    }

    public void start() {
    try {
    ss = new ServerSocket(10000);
    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<clients.size(); i++) {
    Client c = clients.get(i);
    c.send(str);
    //System.out.println(" a string send !");
    }
    /*
    for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
    Client c = it.next();
    c.send(str);
    }
    */
    /*
    Iterator<Client> 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();
    }


    }
    }

    }
    }package com.tianlesoftware.basejava;
    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() {
    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", 10000);
    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();


    }

    }
    }
    以前捣鼓的……,可以参考一下……