我试图使用tcp套接字编程从android客户端接收数据到java服务器,但问题是它没有监听和接收数据。我想连续接收数据。任何人都可以帮忙。
Android客户端:
package com.example.clientserver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Button sendButton;
private EditText messageText;
private String messageToSend;
private ClientSender clientSender;
private Context context;
private Socket socket;
private static String SERVER_IP = "192.168.41.32";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageText = (EditText) findViewById(R.id.editText);
sendButton = (Button) findViewById(R.id.send_button);
context = this.getApplicationContext();
clientSender = new ClientSender(context);
socket = null;
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
messageToSend = messageText.getText().toString()
+ System.getProperty("line.separator");
new ClientSender(context).execute(messageToSend);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ClientSender extends AsyncTask<String, Void, Socket> {
private Socket socket;
private String answer;
private Context context;
private BufferedWriter out;
private BufferedReader in;
public ClientSender(Context context) {
this.context = context;
socket = null;
out = null;
in = null;
}
@Override
protected Socket doInBackground(String... params) {
try {
if (socket == null) {
socket = new Socket(SERVER_IP, 4000);
out = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
}
out.write(params[0]);
out.flush();
answer = in.readLine() + System.getProperty("line.separator");
return socket;
} catch (IOException e) {
e.printStackTrace();
}
return socket;
}
protected void onPostExecute(Socket socket) {
if (socket != null) {
Toast.makeText(context, answer, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Can't connect to server!",
Toast.LENGTH_LONG).show();
}
}
}
}
服务器端:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication4;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Mona
*/
public class Server extends javax.swing.JFrame {
ServerSocket serverSocket;
Socket socket;
int port = 4000;
/**
* Creates new form Server
*/
public Server() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(169, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(158, 158, 158))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(140, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(137, 137, 137))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
System.out.println("start Listening");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//InputStream stream = new BufferedInputStream(socket.getInputStream());
String message = in.readLine();
// byte[] buffer = new byte[1024];
// int size = stream.read(buffer); // blockiert bis Nachricht empfangen
// String data = new String(buffer, 0, size);
System.out.println("strings" + message);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Server.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
如何编写从客户端连续接收字符串数据的服务器。我编写了代码,但没有收到数据。我希望服务器端在点击android的“发送”按钮时接收数据。帮助任何人。