gpt4 book ai didi

java - Swing socket 测试

转载 作者:行者123 更新时间:2023-12-01 17:39:51 27 4
gpt4 key购买 nike

我正在尝试使用 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");

这是服务器应该获取的第一个字符串。但它一直处于等待状态,就好像什么也没收到一样。

最佳答案

您必须在每个 println() 之后使用 flush() 或激活 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");
...

不要忘记服务器...

关于java - Swing socket 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411512/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com