西文数据库:关于聊天室编程的问题

来源:百度文库 编辑:神马品牌网 时间:2024/04/26 12:39:44
大家好 我是一个java新手 编了一个简单的聊天室程序,但是总是有点问题,主要是在客户端或服务器端收取数据,总是需要先按一个回车键,才能收到数据,不知道是什么原因,我把源代码 贴过来 希望大家能帮我解答下 万分感谢
server端
import java.io.*;
import java.net.*;

class JServer{
public static final int PORT = 8080;
BufferedReader in = null;
PrintWriter out = null;
BufferedReader sin = null;
public void init()
throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try {
Socket socket = s.accept();
try {
System.out.println(
"Connection accepted: "+ socket);
in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
sin =new BufferedReader(new InputStreamReader(System.in));
while (true) {

String sr = sin.readLine();
if(sr.equals("END")) break;
out.println(sr);
new receive().start();
}

}
finally {
System.out.println("closing...");
socket.close();
}
} finally {
s.close();
}
}
private class receive extends Thread{
public void run(){
try {String str = in.readLine();
System.out.println (str);
}
catch (Exception ex) {
}

}
}
}

public class Server{
public static void main(String[] args)throws IOException
{
new JServer().init();
}
}
client端
import java.net.*;
import java.io.*;

class JClient {
public static final int PORT = 8080;
BufferedReader in = null;
PrintWriter out = null;
BufferedReader sin = null;
public void init()
throws IOException {
InetAddress addr =
InetAddress.getByName(null);
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, PORT);
try {
System.out.println("socket = " + socket);
in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
sin =new BufferedReader(new InputStreamReader(System.in));
while (true){

String sr = sin.readLine();
if(sr.equals("END")) break;
out.println(sr);
new receive().start();

}
}
finally {
System.out.println("closing...");
socket.close();
}
}
private class receive extends Thread{
public void run(){
try {String str = in.readLine();
System.out.println (str);
}
catch (Exception ex) {
}

}
}
}

public class Client {
public static void main(String[] args)throws IOException
{
new JClient().init();
}
}

看到这么多的代码,对我来说你已经是高手了.