我能够从android客户端将字符串发送到C服务器。 但我无法从服务器返回到Android客户端的响应。 Android客户端没有获取数据。我想"吐司"响应来自c服务器。
服务器代码(c):
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main( int argc, char *argv[] ) {
int sockfd, newsockfd, portno, clilen;
char buffer[256];
char g[255];
char *message;
struct sockaddr_in serv_addr, cli_addr;
int n;
int p;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5011;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("192.168.1.125");
//serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
/* Now bind the host address using bind() call.*/
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR on binding");
exit(1);
}
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
listen(sockfd,5);
clilen = sizeof(cli_addr);
/* Accept actual connection from the client */
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newsockfd < 0) {
perror("ERROR on accept");
exit(1);
}
/* If connection is established then start communicating */
bzero(buffer,256);
n = read( newsockfd,buffer,255 );
if (n < 0) {
perror("ERROR reading from socket");
exit(1);
}
printf("Here is the message: %s\n",buffer);
/* Write a response to the client */
//int man = 12345;
message ="hello\n";
n = write(newsockfd, message,strlen(message));
return 0;
}
**** Android客户端:****
import android.app.Activity;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class ScreenTwo extends Activity {
EditText et;
String txt,ssid,key;
WifiManager wifiManager;
private Socket socket;
private Socket clientSocket;
private BufferedReader input;
static final int SERVERPORT = 5047;
private static final String SERVER_IP = "192.168.1.125";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
new Thread(new ClientThread()).start();
}
public void onClick(View v) {
try {
EdritText et = (EditText) findViewById(R.id.tb1);
Sting str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str + "\n");
out.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read = input.readLine();
Toast.makeText(this, read, Toast.LENGTH_LONG).show();
//ready to receive data from server
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println(in.readLine());
//Toast.makeText(this, in.readLine(), Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onEnterBtn(View v)
{
//Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
et=(EditText)findViewById(R.id.tb1);
txt=et.getText().toString();
Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
Button disp = (Button)findViewById(R.id.dispbtn);
disp.setBackgroundColor(Color.parseColor(txt));
}
public void onbuttonwifi(View v)
{
//Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);
Toast.makeText(this, ipAddress, Toast.LENGTH_LONG).show();
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
提前致谢:)
答案 0 :(得分:0)
String read = input.readLine();
客户端尝试读取一行。但是服务器没有用
发送一行n = write(newsockfd, g,p);
在发送之前将"\n"
添加到字符串变量g
。在确定p
之前。
答案 1 :(得分:0)
首先,此代码仅适用于非常旧的Android设备。现代设备不允许在主线程上进行网络连接,您必须将其移动到单独的线程中。网上有足够的教程来做这件事。
在退出程序之前关闭套接字和文件等通常是一种好习惯。我不相信你会在你编写的代码中违反缓存,但它总是存在风险,所以最佳实践说除非你故意提前终止程序(exit(1)
),否则你应该{{1} }。
您看到的最可能的错误原因是close(newsockfd)
期望在每一行的末尾都有一个行终止符(BufferedReader.readline()
)并且您没有发送一个...来自当用户按下“enter”时,内存\n
不包括行终止符。
根据这个假设,您需要做一些事情来发送行终止符。在发送之前修改字符串或单独发送:
gets()
不要忘记在每次写入和每次读取后都应该检查响应。写作也可能失败:
n = write(newsockfd, "\n", sizeof("\n") - 1);
如果你已经尝试了所有这些并且仍然无法正常工作......
查看双方的输出,确保它们没有打印任何错误。到目前为止,我们对你的回答都是基于这样的假设:“不工作”意味着它的悬挂。如果任何一方都列出了错误,那么就可以更清楚地了解正在发生的事情。
如果它只是挂起,那么我建议你在C中构建一个简单的测试客户端。这样你就可以显示它只在C中工作或者不能......因此你可以显示C代码或android代码无效。如果你能找出哪个技术有问题,你将永远得到更多的帮助。