[英]sending and receiving data over socket
I have two Jtextarea in my code.I have a connect button and on click of connect it gets connected to the server. 我的代码中有两个Jtextarea,我有一个connect按钮,单击connect它将连接到服务器。 I have a send button.
我有一个发送按钮。 When i type anything in the first jtextarea and click send button it should be received back and printed in the second jtextarea.
当我在第一个jtextarea中键入任何内容并单击“发送”按钮时,应将其收回并打印在第二个jtextarea中。
My problem is when i send data first time i am receiving back data properly but when i send data second time i am not receiving it back. 我的问题是,当我第一次发送数据时,我正确地接收了数据,但是当我第二次发送数据时,我没有接收到数据。 When i send the third data i am receiving back the second data and this continues.
当我发送第三个数据时,我正在接收回第二个数据,并且继续进行。
please help.thanks in advance This is my code. 请提前帮助。谢谢。这是我的代码。
public class send extends JFrame
{
Socket s;
int port=3000;
String host="192.168.1.3"
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run(){
send s=new send();
s.setvisible(true);
}
});
}
public send() {
setDrfaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setBounds(100,100,400,600);
Jpanel ContentPane=new Jpanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5);
setContentPane(contentpane);
contentPane.setLayout(null);
JButton connect=new Jbutton("connect");
connect.setBounds(15,10,100,40);
connect.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e{
try{
addr=InetAddress.getByName(host);
s=new Socket(addr,port);
}
catch(UnknownHostException e1)
{
e1.printStackTrace();
}
catch(IOException e2)
{
e2.printStackTrace();
}
}
});
contentPane.add(connect);
JTextArea area=new JtextArea();
area.setBounds(15,70,100,40);
contentPane.add(area);
JButton btn=new JButton("send"):
btn.setBounds(15,70,170,80);
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(!(area.getText().trim.isEmpty())
{
try
{
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(area.getText());
InputStreamReader in=new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(in);
String msg=br.readLine();
if(msg!=null)
{
txt.append("s:"+area.getText()+"\n");
txt.append(msg+"\n");
area.setText("");
}
catch(IOException e3)
{
e3.printStackTrace();
}
}
}
});
contentPane(btn);
JTextArea txt=new JtextArea();
txt.setBounds(15,210,290,300);
contentPane.add(txt);
}
}
Just flush the stream: 只需刷新流:
ps.println(area.getText());
ps.flush();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.