上一篇是简单的socket连接, 现在是通信问题了;本篇解决的问题是:BufferedReader 读取不到信息?
下面我粘出部分部分客户端 + 服务器端的代码
Android客户端:
//连接ip
Connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(){
@Override
public void run() {
try {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
socket = new Socket("10.13.56.180",12345);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Message m = new Message();
m.what = 0x122;//接收服务器发过来的数据
m.obj ="连接成功!"+ reader.readLine();//
handler.sendMessage(m);
} catch (IOException e) {
Log.e("connect","连接失败");
e.printStackTrace();
}
}
}.start();
}
});
Java 服务器端
package com.android.service;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class serverListener extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket serverSocket = new ServerSocket(12345);
while(true){
Socket socket = serverSocket.accept();
//连接成功
// JOptionPane.showMessageDialog(null, "你已连接到了本机的12345端口");
System.out.println("已连接一名客户");
//将socket传递给先的线程
ChatSocket cSocket = new ChatSocket(socket);
cSocket.start();
cSocket.out("你已经连到了本服务器");
ChatManager.getManager().add(cSocket);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
效果图,点击连接后,text view中显示相关信息
解决办法:
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.readLine()是一次读取一行 ,也是说遇到换行符才会停止,
按照我的程序cSocket.out("你已经连到了本服务器");改成cSocket.out("你已经连到了本服务器\n");就可以正常读取,并且本程序也不会因socket连接超时而连接失败!