求解决客户端写出的字符串为什么不能在服务器端控制台显示。
代码如下:
客户端:import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatClient extends Frame {	
	Socket s = null;
	DataOutputStream dos = null;	
	TextField tfTxt = new TextField();
	TextArea tfContent = new TextArea();
	public static void main(String[] args) {
		new ChatClient().launchFrame();
	}	
	public void launchFrame() {
		setBounds(300, 300, 400, 400);
		add(tfTxt, BorderLayout.SOUTH);
		add(tfContent, BorderLayout.NORTH);
		pack();
		this.addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e) {
				disConnect();
				System.exit(0);
			}			
		}
		);
		tfTxt.addActionListener(new TFListener());
		setVisible(true);
		connect();
	}	
	public void connect() {
		try {
			s = new Socket("127.0.0.1", 8888);
			dos = new DataOutputStream(s.getOutputStream());
System.out.println("connected");
		} catch (
UnknownHostException e) {
			e.printStackTrace();
		} catch (
IOException e) {
			e.printStackTrace();
		}
	}
	public void disConnect() {
		try {
			dos.close();
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}		
		private class TFListener implements ActionListener {
			@Override
			public void actionPerformed(ActionEvent e) {
				String str = tfTxt.getText().trim();
				tfContent.setText(str);
				tfTxt.setText("");
				try {
					dos.writeUTF(str);
					dos.flush();
				}	catch(IOException ae) {
					ae.printStackTrace();
				}
			}			
		}
}
服务器端:
import java.io.*;
import java.net.*;
public class ChatServer {
	public static void main(String[] args) {
		boolean started = false;
		try {
			ServerSocket ss = new ServerSocket(8888);
			started = true;
			while(started) {
				boolean bconnected = false;
				Socket s = ss.accept();
System.out.println("a client content");
				bconnected = true;
				DataInputStream dis = new DataInputStream(s.getInputStream());
				while(bconnected) {
					String str = dis.readUTF();
					System.out.println(str);
				}
				dis.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
------解决方案--------------------你在客户端是不是没有创建连接调用这个函数哦:
public void connect()  
------解决方案--------------------你客户端有问题,没有放数据进去,服务器就一直等着
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
System.out.println("connected");} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
改为
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello,kitty!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
------解决方案--------------------
没有问题啊,用你的代码测试了一下,服务器是输出了客户端传过去的字符串。建议你检查一下你的socket是否连接正确。这句有输出么?
Java code
System.out.println("connected");