新手白白的问题
package socket;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class MyClient extends Frame implements ActionListener
{
public static void main(String[] args) {
new MyClient();
}
Socket clientSocket;
PrintStream os;
BufferedReader is;
String s;
TextArea receArea,sendArea;
Button myButton = new Button( "发送 ");
public MyClient()
{
setTitle( "Client Window ");
setLayout(new BorderLayout());
this.addWindowListener(new WinAdptClient(this));
myButton.addActionListener(this);
receArea = new TextArea(10,50);
sendArea = new TextArea(10,50);
//add( "North ",myLabel);
add( "South ",myButton);
add( "North ",receArea);
add( "Center ",sendArea);
setResizable(false);
pack();
setVisible(true);
connect();
}
public void connect()
{
try
{
clientSocket = new Socket( "MyHost ",8888);
os = new PrintStream(
new BufferedOutputStream(clientSocket.getOutputStream()));
is = new BufferedReader(new InputStreamReader(clientSocket
.getInputStream()));
while(true){
try{
s = is.readLine();
receArea.append(s+ "\n ");
}catch(Exception e){
break;
}
}
//receArea.setText( "rece over ");
}
catch(Exception e){
System.out.println( "rece error ");
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == myButton)
{
try
{
System.out.println(receArea.getText());
os.print(sendArea.getText());
os.flush();
sendArea.setText( " ");
}
catch(Exception ex){}
}
}
}
class WinAdptClient extends WindowAdapter
{
MyClient m_Parent;
WinAdptClient(MyClient p)
{
m_Parent = p;
}
public void windowClosing(WindowEvent e)
{
try
{
m_Parent.os.println( "Bye ");
m_Parent.os.flush();
m_Parent.is.close();
m_Parent.os.close();
m_Parent.clientSocket.close();
m_Parent.dispose();
System.exit(0);
}
catch(Exception ex){
System.out.println( "error close ");
}
}
}
1.s = is.readLine();
这如果没有数据,就会导致阻塞;
那么如果这个时候我点了界面上的“X”关闭窗口,会运行m_Parent.is.close();
但是这个时候is被阻塞了,导致is.close()也阻塞了,无法关闭窗口了,怎么解决比较地道???
我想了两种方法,一是设置超时时间;二是直接exit(0)了,不去一个个关流了。
不知道够不够地道?
2.os.print(sendArea.getText());
os.flush();
不能发送数据出去,但是点关闭以后,所有的数据都一次发过去了,就如同os.flush();没有起作用一样。
但是把sendArea替换为receArea,就正常了。不知道怎么回事?
------解决方案--------------------学习
------解决方案--------------------up
------解决方案--------------------