我正在尝试使用Swing的程序。
我使用套接字连接到服务器,客户端有gui代码。
public class FactClient extends JFrame implements ActionListener
{
Socket s;
InputStream in;
OutputStream os;
Scanner sin;
PrintWriter out;
JPanel jp;
JTextField jt;
JButton jb;
JLabel jl;
FactClient()
{
jp = new JPanel();
jt = new JTextField("Enter number",15);
jb = new JButton("Compute Factorial");
jl = new JLabel("Answer");
jb.addActionListener(this);
jp.add(jt);
jp.add(jb);
jp.add(jl);
add(jp);
setVisible(true);
setSize(200,100);
try
{
s = new Socket("localhost",8189);
try
{
in = s.getInputStream();
os = s.getOutputStream();
sin = new Scanner(in);
out = new PrintWriter(os);
out.println("Done with the bingo");
}
finally {}
}
catch(Exception e)
{
System.out.println("Error in client code " + e );
}
}
public void actionPerformed(ActionEvent ae)
{
try {
System.out.println("Connection established " + jt.getText());
String t = jt.getText();
out.println("Ashish");
System.out.println("Data Send");
t = sin.nextLine();
jl.setText(t);
}
catch(Exception e)
{
System.out.println("Error in client code " + e );
}
}
public static void main(String args[])
{
new FactClient();
}
}import java.io.*;
import java.util.*;
import java.net.*;
public class FactServer
{
public static void main(String args[])
{
ServerSocket s;
Socket socket;
try
{
s= new ServerSocket(8189);
socket = s.accept();
try
{
InputStream in = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Scanner sin = new Scanner(in);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
PrintWriter ou = new PrintWriter(os);
System.out.println("Connection Established : Stream initailzed");
try
{
String data = br.readLine();
System.out.println("Data Recvd." + data);
data = br.readLine();
}
catch(Exception e)
{
System.out.println("EEEEEEEEEEEEE" + e);
}
//int fact = data +20;
ou.println("40");
}
catch (Exception e)
{
System.out.println("ERROR :P");
}
finally
{
socket.close();
}
}
catch(Exception e)
{
System.out.println("ERROR" + e);
}
}
}服务器代码只读取我使用System.out.println发送的数据。但问题是,它挂起了;服务器永远得不到数据!
out.println("Done with the bingo");这是服务器应该获得的第一个字符串。但是它保持在等待状态,好像什么都没有收到一样。
发布于 2010-03-09 20:06:51
您必须在每个flush()之后使用println(),或者激活PrintWriter上的自动刷新,以便真正发送数据:
...
out = new PrintWriter(os);
out.println("Done with the bingo");
out.flush();
...或
...
out = new PrintWriter(os, true); // autoflush
out.println("Done with the bingo");
...别忘了服务器..。
发布于 2010-03-09 20:46:41
像卡洛斯说的那样,在你的PrintWriter中启用自动冲洗应该可以解决你的主要问题。还有几个你可能会考虑的想法:
如果希望服务器逻辑处理多个客户端请求,则将其封装在一个循环(例如while(true) {...})中,并在一个单独的线程中处理每个请求。
由于您是在Swing事件Dispatch (即actionPerformed()方法)上发出客户端请求,所以可以考虑将其包装在Runnable或SwingWorker中,这样就不会阻塞调度线程。否则,您可能会注意到,在发生套接字通信时,UI似乎挂起或未绘制。
https://stackoverflow.com/questions/2411512
复制相似问题