服务器只能接收到第一次发送的信息,
服务器的代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Ser extends JFrame
{ private JTextArea ta;
public Ser()
{
Container c=getContentPane();
c.setLayout(null);
ta=new JTextArea(10,10);
ta.setBounds(10,10,370,250);
c.add(ta);
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void getMessage()
{
ServerThread cst=new ServerThread();
cst.start();
}
public static void main(String args[])
{
Ser s=new Ser();
s.getMessage();
}
class ServerThread extends Thread //接收信息的线程类
{
ServerSocket ss=null;
Socket s=null;
BufferedReader in=null;
PrintWriter out=null;
public ServerThread()
{
System.out.println("服务器已启动");
}
public void run()
{
try{
ss=new ServerSocket(8888);
s=ss.accept();
in=new BufferedReader (new InputStreamReader(s.getInputStream()) );
out=new PrintWriter (s.getOutputStream());
String str=in.readLine();
if(!str.equals("bye"))
{
ta.setText(str);
str=in.readLine();
}
}
catch(IOException ioe){ioe.printStackTrace();}
finally
{try{
out.close();
in.close();
s.close();
}
catch(IOException eee){eee.printStackTrace();}
}
}
}
}
客户端代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client extends JFrame implements ActionListener
{
private JButton b;
private JTextArea ta;
Socket s;
BufferedReader in;
PrintWriter out;
public Client()
{
Container c=getContentPane();//界面设置
c.setLayout(null);
b=new JButton("发送");
b.setBounds(150,300,100,30);
b.addActionListener(this);
c.add(b);
ta=new JTextArea(10,10);
ta.setBounds(10,10,370,250);
c.add(ta);
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ee)//点击发送的消息响应
{
if(ee.getSource()==b)
{
try{
s=new Socket("localhost",8888);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream(),true);
out.print(ta.getText());
ta.setText("");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{try{
out.close();
in.close();
s.close();
}
catch(IOException eee){eee.printStackTrace();}
}
}
}
public static void main(String args[])
{
Client cc=new Client();
}
}