socket 服务端无法接收数据
本人写了一个项目,通过Socket用Android发出一个String,运行在本机上的服务端接受并写入文件中,但是客服端写不出数据,是在 os.write((bin.getText().toString()).getBytes("utf-8"));
这条代码卡住了,发不出数据,也无法执行后面代码,求大帮忙呀!
客户端
bu1.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
try{
s=new Socket("192.168.137.49",37000);
os=s.getOutputStream();
in=s.getInputStream();
os.write((bin.getText().toString()).getBytes("utf-8"));
bin.setText("");
}catch(Exception e){
e.printStackTrace();
}
}
});
服务端:
public class SimpleServer {
public static void main(String[]args)throws Exception
{
ServerSocket ss=new ServerSocket(37000);
while(true)
{
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream(),"utf-8"));
FileOutputStream fos = null;
BufferedWriter bw = null;
String content=br.readLine();
while((content!=null)&&(content.length()!=0))
{
System.out.println(content);
try {
File file = new File("d:\\ok.txt");
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
}catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
catch (IOException ioe){
ioe.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
if (fos != null)
fos.close();
}catch (IOException ie) {
}
}
}
}
}
}
[解决办法]
os.write((bin.getText().toString()).getBytes("utf-8"));
后面加上
os.flush();
[解决办法]
os.write((bin.getText().toString()).getBytes("utf-8"));
os.flush();