当前位置:编程学习 > JAVA >>

求前辈帮忙排错(点对点socket聊天工具)

我最近自己写好的基于简单socket和tcp协议上的点对点聊天工具。程序没有语法错误,通过编译后,运行后,发现会实现连接成功的提示,但是不能互发信息。测试了好几天,我总是觉得肯定是那个地方的逻辑性错误了。但是一直找不到在哪里。并且不知道该如何的修改了。求各位前辈指导,小弟新手。
这是服务器代码:Server.java

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import javax.swing.WindowConstants;
public class Server extends javax.swing.JFrame
{
private static final long serialVersionUID = 1L;

private JTextArea displayArea;

private JLabel jLabel1;

private JLabel jLabel2;

private JTextField portT;

private JTextField enterFild;

private JButton fasong;

private JButton chuSong;

private JTextField ipDree;

private PrintWriter output;

private BufferedReader input;

private ServerSocket server;

private Socket connection;

public Server()
{
super();
initGUI();
        
enterFild.addActionListener(new ActionListener()
{
// 向客户端发送数据
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
sendData(e.getActionCommand());
enterFild.setText("");
}
});
}

// 创建和运行服务器
public void runServer()
{
try
{
waitForConnection();
//getStreams();
ProcessConnection();
closeConnection();


} catch (EOFException e)
{
System.out.println("点击终止连接!");
} catch (IOException e)
{
e.printStackTrace();
}

}

// 等待连接请求!
public void waitForConnection() throws IOException
{

server = new ServerSocket(5000, 100);

displayArea.setText("等待连接\n");
connection = server.accept();
displayArea.append("连接中来自于"+ connection.getInetAddress().getHostName());
}

/*public void getStreams() throws IOException
{
// 创建输出数据流对象
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// 创建输入流数据对象
ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
displayArea.append("\n获得文本内容!\n");
}*/

// 处理和客户端的连接
public void ProcessConnection() throws IOException
{
   
String message = "服务器>>>连接成功!";
//output.writeObject(message);
//output.flush();
enterFild.setEnabled(true);

// 处理客户端发来的数据
do
{
try
{
// 创建输出数据流对象
output = new PrintWriter(connection.getOutputStream());
output.flush();
// 创建输入流数据对象
input = new BufferedReader(new InputStreamReader(System.in));
displayArea.append("\n获得文本内容!\n");

message = (String) input.readLine();
displayArea.append("\n" + message);
displayArea.setCaretPosition(displayArea.getText().length());

} catch (IOException e)
{
displayArea.append("\n未知的连接对象!");
}
} while (!message.equals("服务器>>>终止连接!"));

}

// 向客户发送信息
public void sendData(String message)
{

try
{
// connection= new Socket();
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); // 在构造函数里面初始化output
output.writeObject("服务器>>>" + message);
output.flush();
displayArea.append("\n服务器>>>" + message);

} catch (IOException e)
{
displayArea.append("\n错误的连接对象!");
}
}

public void closeConnection() throws IOException 
{
displayArea.append("\n用户终止连接!");
enterFild.setEnabled(false);
output.close();
input.close();
connection.close();
}

// 创建服务器程序
public static void main(String[] args)
{
Server application = new Server();// +
/*
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//Server inst = new Server();
inst.setLocationRelativeTo(null);
inst.setVisible(true);

if(application!=null)
{
application.setLocationRelativeTo(null);
}
}
});

*/

//Server application = new Server();// +
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

application.setVisible(true);

application.runServer();

}

// GUI界面设计
private void initGUI()
{
try
{
GridBagLayout thisLayout = new GridBagLayout();
thisLayout.rowWeights = new double[] { 0.1, 0.1, 0.1, 0.1 };
thisLayout.rowHeights = new int[] { 7, 7, 7, 7 };
thisLayout.columnWeights = new double[] { 0.1, 0.1, 0.1, 0.1 };
thisLayout.columnWidths = new int[] { 7, 7, 7, 7 };
getContentPane().setLayout(thisLayout);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("\u804a\u5929\u5c0f\u5de5\u5177(\u670d\u52a1\u5668\u7aef)");
{
JScrollPane jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1, new GridBagConstraints(0, 0, 4, 2, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
{
displayArea = new JTextArea();
jScrollPane1.setViewportView(displayArea);
{
JSlider Slider = new JSlider();
displayArea.add(Slider);
displayArea.setEditable(false);
Slider.setPreferredSize(new java.awt.Dimension(-405, 0));
}
}
}
{
jLabel1 = new JLabel();
getContentPane().add(
jLabel1,
new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jLabel1.setText(" IP \u5730\u5740\uff1a");
jLabel1.setFont(new java.awt.Font("微软雅黑", 0, 16));
}
{
jLabel2 = new JLabel();
getContentPane().add(
jLabel2,
new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jLabel2.setText("\u7aef\u53e3\u5730\u5740\uff1a");
jLabel2.setFont(new java.awt.Font("微软雅黑", 0, 16));
}
{
ipDree = new JTextField();
getContentPane().add(
ipDree,
new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
ipDree.setText("127.0.0.1");
ipDree.setBackground(new java.awt.Color(0, 255, 255));
ipDree.setFont(new java.awt.Font("微软雅黑", 0, 14));
ipDree.setEnabled(false);
}
{
portT = new JTextField();
getContentPane().add(
portT,
new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
portT.setText("5000");
portT.setBackground(new java.awt.Color(0, 255, 255));
portT.setFont(new java.awt.Font("微软雅黑", 0, 14));
portT.setEnabled(false);
}
{
chuSong = new JButton();
getContentPane().add(
chuSong,
new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
chuSong.setText("\u4f20\u9001\u6587\u4ef6");

chuSong.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent evt)
{
// TODO Auto-generated method stub
try
{
JFileChooser file = new JFileChooser();
file.showOpenDialog(null);
File fl = file.getSelectedFile();
byte b[] = new byte[(int) fl.length()];
FileInputStream fileinput = new FileInputStream(fl);
fileinput.read(b);
fileinput.close();
String s = new String(b);
System.out.print(s);
file.showSaveDialog(null);
File fout = file.getSelectedFile();
FileOutputStream fileout = new FileOutputStream(fout);
fileout.write(b);
fileout.close();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
{
fasong = new JButton();
getContentPane().add(
fasong,
new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
fasong.setText("\u53d1\u9001\u4fe1\u606f");
fasong.addMouseListener(new MouseListener()
{

@Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
sendData(enterFild.getText());
}

@Override
public void mousePressed(MouseEvent e)
{
// TODO Auto-generated method stub
}

@Override
public void mouseReleased(MouseEvent e)
{
// TODO Auto-generated method stub
}

@Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}

@Override
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub
}
});
}
{
enterFild = new JTextField();
getContentPane().add(
enterFild,
new GridBagConstraints(0, 3, 4, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
enterFild.setFont(new java.awt.Font("华文行楷", 0, 18));
enterFild.setEnabled(true);
enterFild.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
sendData(event.getActionCommand());
}
});
}
pack();
this.setSize(393, 293);
} catch (Exception e)
{
// add your error handling code here
e.printStackTrace();
}
}

}

socket 排错 --------------------编程问答-------------------- 这是客户端代码:Client.java

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import javax.swing.WindowConstants;

public class Client extends javax.swing.JFrame
{
/**
 * 
 */
private static final long serialVersionUID = 1L;

private JTextArea displayArea;

private JLabel jLabel1;

private JLabel jLabel2;

private JTextField ipDree;

private JTextField portT;

private JTextField enterFild;

private JButton fasong;

private JButton chuSong;

private PrintWriter output;

private BufferedReader input;

private String message = "";

private String chatServer;

private Socket client;

/**
 * Auto-generated main method to display this JFrame
 */

public Client(String host)
{ // +
super();
initGUI();
}

// 连接服务器、接收、处理信息
public void runClient()
{
try
{
// 第一步,创建套接字
connectToServer();
// 第二步,获得输入输出对象流
//getStreams();
// 第三步,处理连接
processConnection();
// 第四步,关闭连接
closeConnection();
} catch (EOFException eofException)
{
System.out.println("服务器终止连接!");
} catch (IOException e)
{
e.printStackTrace();
}
}

// 连接到服务器
public void connectToServer() throws IOException
{
displayArea.setText("尝试连接服务器!");
client = new Socket(InetAddress.getByName(chatServer), 5000);

//这里的逻辑不对。
displayArea.append("已经连接成功上:" + client.getInetAddress().getHostName());

}

// 接收和发送数据
//public void getStreams() throws IOException // 获取字符串实现方法
//{
//}

// 处理和服务器的连接
public void processConnection() throws IOException
{
enterFild.setEnabled(true);
do
{
try
{
output = new PrintWriter(client.getOutputStream());
output.flush();
input = new BufferedReader(new InputStreamReader(System.in));
displayArea.append("\nI/O流 已经获得 !");

message = input.readLine();
displayArea.append("\n" + message);
displayArea.setCaretPosition(displayArea.getText().length());
} catch (Exception e)
{
displayArea.append("\n得到未知的对象类型!\n");
}
} while (!message.equals("exit"));
}

// 关闭流对象和连接对象
public void closeConnection() throws IOException
{
displayArea.append("\n断开连接!");
output.close();
input.close();
client.close();
}

// 向服务器发送数据
public void sendData(String message)
{

try
{
message = enterFild.getText();

//System.out.println("msg:" + message);
output.flush();
output.println("客户端>>>" + message);

displayArea.append("\n客户端>>>" + message);
} catch (Exception e)
{
displayArea.append("\n不可写的目标!");
}
}

public static void main(String[] args)
{
/*
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Client inst = new Client(null);// +
inst.setLocationRelativeTo(null);
inst.setVisible(true);

}
});
*/

Client application;
// Client p = new Client(); //初始化非静态内部类声明
if (args.length == 0)
application = new Client("127.0.0.1");
else
application = new Client(args[0]);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

application.setVisible(true);

application.runClient();
}

// GUI界面设计
private void initGUI()
{
try
{
GridBagLayout thisLayout = new GridBagLayout();
thisLayout.rowWeights = new double[] { 0.1, 0.1, 0.1, 0.1 };
thisLayout.rowHeights = new int[] { 7, 7, 7, 7 };
thisLayout.columnWeights = new double[] { 0.1, 0.1, 0.1, 0.1 };
thisLayout.columnWidths = new int[] { 7, 7, 7, 7 };
getContentPane().setLayout(thisLayout);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("\u804a\u5929\u5c0f\u5de5\u5177(\u5ba2\u6237\u7aef)");

{
JScrollPane jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1, new GridBagConstraints(0, 0, 4, 2, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
{
displayArea = new JTextArea();
jScrollPane1.setViewportView(displayArea);
{
JSlider Slider = new JSlider();
displayArea.add(Slider);
displayArea.setEditable(false);
Slider.setPreferredSize(new java.awt.Dimension(-405, 0));
}
}
}
/*{
displayArea = new JTextArea();
getContentPane().add(
displayArea,
new GridBagConstraints(0, 0, 4, 2, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
displayArea.setEnabled(false);
displayArea.setBackground(new java.awt.Color(255, 255, 255));

}*/
{
jLabel1 = new JLabel();
getContentPane().add(
jLabel1,
new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jLabel1.setText(" IP \u5730\u5740\uff1a");
jLabel1.setFont(new java.awt.Font("微软雅黑", 0, 16));
}
{
jLabel2 = new JLabel();
getContentPane().add(
jLabel2,
new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jLabel2.setText("\u7aef\u53e3\u5730\u5740\uff1a");
jLabel2.setFont(new java.awt.Font("微软雅黑", 0, 16));
}
{
ipDree = new JTextField();
getContentPane().add(
ipDree,
new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
ipDree.setText("127.0.0.1");
ipDree.setBackground(new java.awt.Color(0, 255, 255));
ipDree.setFont(new java.awt.Font("微软雅黑", 0, 14));
ipDree.setEnabled(false);
}
{
portT = new JTextField();
getContentPane().add(
portT,
new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
portT.setText("5000");
portT.setBackground(new java.awt.Color(0, 255, 255));
portT.setFont(new java.awt.Font("微软雅黑", 0, 14));
portT.setEnabled(false);
}
{
chuSong = new JButton();
getContentPane().add(
chuSong,
new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
chuSong.setText("\u4f20\u9001\u6587\u4ef6");

chuSong.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent evt)
{
// TODO Auto-generated method stub
try
{
JFileChooser file = new JFileChooser();
file.showOpenDialog(null);
File fl = file.getSelectedFile();
byte b[] = new byte[(int) fl.length()];
FileInputStream fileinput = new FileInputStream(fl);
fileinput.read(b);
fileinput.close();
String s = new String(b);
System.out.print(s);
file.showSaveDialog(null);
File fout = file.getSelectedFile();
FileOutputStream fileout = new FileOutputStream(fout);
fileout.write(b);
fileout.close();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
{
fasong = new JButton();
getContentPane().add(
fasong,
new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
fasong.setText("\u53d1\u9001\u4fe1\u606f");
fasong.addMouseListener(new MouseListener()
{

@Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
sendData(message);
enterFild.setText("");
}

@Override
public void mousePressed(MouseEvent e)
{
// TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e)
{
// TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub

}
});

}
{
enterFild = new JTextField();
getContentPane().add(
enterFild,
new GridBagConstraints(0, 3, 4, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
enterFild.setFont(new java.awt.Font("华文行楷", 0, 18));

enterFild.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
//sendData(event.getActionCommand());// 将定义方法sendData
sendData(enterFild.getText());
enterFild.setText("");
}
});

}
pack();
this.setSize(393, 293);
} catch (Exception e)
{
// add your error handling code here
e.printStackTrace();
}
}

}
--------------------编程问答-------------------- 界面跟业务放在一起那么乱!!!! --------------------编程问答-------------------- fasong.addMouseListener(new MouseListener() 这些应该写成


fasong.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub

}
});

--------------------编程问答-------------------- 我看了一下,你的思想完全错了!!!!!
服务端必须实时监控着客户端,

 server = new ServerSocket(5000, 100);                  
 displayArea.setText("等待连接\n");         
connection = server.accept(); 
应该改成
 server = new ServerSocket(5000, 100);                  
 displayArea.setText("等待连接\n");   
while(true){
    connection = server.accept(); 
}   

另外还有必须加入多线程,你的用来用处都是一个线程   
--------------------编程问答--------------------  楼主主要是在网络接收和发送有点乱,暂不考虑文件传送,改了几个地方,可以正常发送和接收,楼主试试:
服务器端改动的部分代码:

  public void runServer()
    {
        try
        {                            
                waitForConnection();
                getStreams();//-----------------------加上----  1
                ProcessConnection();
                closeConnection();
                 
             
        } catch (EOFException e)
        {
            System.out.println("点击终止连接!");
        } catch (IOException e)
        {
            e.printStackTrace();
        }
         
    }
 
    // 等待连接请求!
    public void waitForConnection() throws IOException
    {
        server = new ServerSocket(5000, 100);
        displayArea.setText("等待连接\n");
        connection = server.accept();
        displayArea.append("连接中来自于"+ connection.getInetAddress().getHostName());
    }
 
    public void getStreams() throws IOException  //---------------- 加上  ------- 2
    {
        // 创建输出数据流对象
        output = new PrintWriter(connection.getOutputStream()); // ---------改用PrintWriter ---------3
        //output.flush();//--------------                   没用   ---------4
        // 创建输入流数据对象
        input = new BufferedReader(new InputStreamReader(connection.getInputStream())); //------------  用BufferedReader ----5
        displayArea.append("\n获得文本内容!\n");
    }
 
    // 处理和客户端的连接
    public void ProcessConnection() throws IOException
    {
        
        String message = "服务器>>>连接成功!";
        enterFild.setEnabled(true);
         
        // 处理客户端发来的数据
        do
        {
            try
            {
                // 创建输出数据流对象
                //output = new PrintWriter(connection.getOutputStream());   // -----这块是接收 ------6
                //output.flush();
                // 创建输入流数据对象
                //input = new BufferedReader(new InputStreamReader(System.in));  // ----这块乱了,我们是要对方网络的内容,不是键盘输入 ----7
                displayArea.append("\n获得文本内容!\n");
                 
                message = input.readLine();//----------------------- 没必要转换(String)
                displayArea.append("\n" + message);
                displayArea.setCaretPosition(displayArea.getText().length());
                 
            } catch (IOException e)
            {
                displayArea.append("\n未知的连接对象!");
            }
        } while (!message.equals("服务器>>>终止连接!"));
         
    }
 
    // 向客户发送信息
    public void sendData(String message)
    {
 
        //try//------------------ 不需捕获异常-----------------------8 
        //{
            // connection= new Socket();
            //ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); // 在构造函数里面初始化output  ---已经初始化 9
            output.println("服务器>>>" + message);
            output.flush();
            displayArea.append("\n服务器>>>" + message);
             
        //} catch (IOException e)
        //{
          //  displayArea.append("\n错误的连接对象!");
        //}
    }
 


后边按鼠标发送的地方加了一句:

                   @Override
                    public void mouseClicked(MouseEvent e)
                    {
                        // TODO Auto-generated method stub
                        sendData(enterFild.getText());
                        enterFild.setText("");//------------------ 发送完清空  ------10
                    }
 
--------------------编程问答-------------------- 客户端改动部分:

     public void runClient()
    {
        try
        {
            // 第一步,创建套接字
            connectToServer();
            // 第二步,获得输入输出对象流
            getStreams();  //------------------ 保留 -------------------------------------- 1
            // 第三步,处理连接
            processConnection();
            // 第四步,关闭连接
            closeConnection();
        } catch (EOFException eofException)
        {
            System.out.println("服务器终止连接!");
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
 
    // 连接到服务器
    public void connectToServer() throws IOException
    {
        displayArea.setText("尝试连接服务器!");
        client = new Socket(InetAddress.getByName(chatServer), 5000);
         
        //这里的逻辑不对。
        displayArea.append("已经连接成功上:" + client.getInetAddress().getHostName());
         
    }
 
    // 接收和发送数据
    public void getStreams() throws IOException // 获取字符串实现方法  ------- 加上  --------2
    {
        output = new PrintWriter(client.getOutputStream());
        input = new BufferedReader(new InputStreamReader(client.getInputStream()));
        displayArea.append("\nI/O流 已经获得 !");
    }
 
    // 处理和服务器的连接
    public void processConnection() throws IOException
    {
        enterFild.setEnabled(true);
        do
        {
            try
            {
                /*output = new PrintWriter(client.getOutputStream());  //---- 我们直接从网络接收,不要键盘输入。------- 3
                output.flush();
                input = new BufferedReader(new InputStreamReader(System.in));
                displayArea.append("\nI/O流 已经获得 !");
                 */
                message = input.readLine();
                displayArea.append("\n" + message);
                displayArea.setCaretPosition(displayArea.getText().length());
            } catch (Exception e)
            {
                displayArea.append("\n得到未知的对象类型!\n");
            }
        } while (!message.equals("exit"));
    }
 
    // 关闭流对象和连接对象
    public void closeConnection() throws IOException
    {
        displayArea.append("\n断开连接!");
        output.close();
        input.close();
        client.close();
    }
 
    // 向服务器发送数据
    public void sendData(String message)
    {
 
        try
        {
            message = enterFild.getText();
             
            //System.out.println("msg:" + message);

            output.println("客户端>>>" + message);
            output.flush();//---------------------------- 放在后边 -------4
             
            displayArea.append("\n客户端>>>" + message);
        } catch (Exception e)
        {
            displayArea.append("\n不可写的目标!");
        }
    }
 
 
--------------------编程问答-------------------- 发下我刚写的代码,版主看一下吧

package com.whz.client;

import java.io.ObjectOutputStream;
import java.net.Socket;

public class AppClient {
Socket  socket = null;
public AppClient() {
try {
new ClientFrame();
socket = new Socket("192.168.1.186",1001);//修改成你自己的服务器ip,最好能写宽带连接ip或者本地连接ip
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeObject("admin登录成功");
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new AppClient();
}
}




package com.whz.client;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientFrame extends JFrame implements ActionListener{
JTextField textField = null;
JTextArea area = null;
public ClientFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 300);
area = new JTextArea(12, 1);
area.setSize(400,200);
area.setAutoscrolls(true);
area.setEditable(false);
getContentPane().add(area,BorderLayout.NORTH);
JPanel panel = new JPanel();
textField = new JTextField(30);
textField.setSize(250, 80);
JButton button = new JButton("发送");
button.setSize(150, 80);
button.addActionListener(this);
panel.add(textField);
panel.add(button);
getContentPane().add(panel,BorderLayout.SOUTH);
setTitle("客户端");
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String message = textField.getText();
String all_message = area.getText();
try {
Socket socket = new Socket("192.168.1.186", 1001);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeObject(message);
area.setText(message + "\n" + all_message);
textField.setText("");
this.validate();
socket.close();
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
}



package net.whz.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class AppServer extends Thread{
ServerSocket  serverSocket= null;
Socket socket = null;
ServerFrame serverFrame = null;
public AppServer() {
try {
serverFrame = new ServerFrame();
serverSocket = new ServerSocket(1001);
serverFrame.area.setText("服务器启动成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(true){
socket = serverSocket.accept();
conn(socket);//多用户时,这个方法也必须多线程,需要新建一个线程类
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public void conn(Socket socket2) {
try {
// TODO Auto-generated method stub
String message = serverFrame.area.getText();
ObjectInputStream inputStream = new ObjectInputStream(socket2
.getInputStream());
String mess = (String) inputStream.readObject();
serverFrame.area.setText(message + "\n" + mess);
serverFrame.validate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
try {
socket2.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}


public static void main(String[] args) {
new AppServer();
}
}



package net.whz.server;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ServerFrame extends JFrame{
JTextArea area = null;
public ServerFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(500, 100, 500, 300);
area = new JTextArea(12, 1);
area.setSize(400,200);
area.setAutoscrolls(true);
area.setEditable(false);
getContentPane().add(area,BorderLayout.NORTH);
JPanel panel = new JPanel();
JTextField textField = new JTextField(30);
textField.setSize(250, 80);
JButton button = new JButton("发送");
button.setSize(150, 80);
panel.add(textField);
panel.add(button);
getContentPane().add(panel,BorderLayout.SOUTH);
setTitle("服务器");
setVisible(true);
}

}


补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,