2

我试图通过套接字连接 2 个设备,但它从来没有用过。其中一个设备是服务器,它将配置(IP 和监听的端口)保存在数据库上,然后另一个设备,客户端,与数据库连接并进行配置连接。

数据库查询和回显工作正常(PHP),但打开客户端套接字的方法不起作用,它没有时间连接并引发异常。我不知道是ServerSocket没有收到请愿还是ClientSocket没有发送...

下面的代码:(有点糟糕,但用于测试)。

服务器代码:

public class Server{

private int puerto = 4567;

private ServerSocket serverSocket;


public void conectar() {

    try {

        serverSocket = new ServerSocket(puerto);

        while (true) {

            Log.i("SocketServer", "escuchando");

            Socket cliente = serverSocket.accept(); 

            Log.i("Socket","Cliente ha conectado"); 

            BufferedReader ent = new BufferedReader(new InputStreamReader(
                    cliente.getInputStream())); 


            String linea = ent.readLine(); 

            Log.i("Cliente", "Cliente envia=" + linea);

            cliente.close(); 

            Log.i("Servidor","Cliente desconectado");
        }

    } catch (IOException e) {

        Log.e("Error", "Error en el servidor");

    }
}

客户端代码:

public class Cliente {

private int puerto;

private InetAddress direccion;

public Cliente(int puerto, InetAddress direccion){

    this.puerto = puerto;

    this.direccion = direccion;

}

public void conectar(){

    try{

    Socket cliente = new Socket(direccion, puerto);

    Log.i("Cliente", "Conectado");

    conectado = true;

    PrintWriter salida=new PrintWriter(cliente.getOutputStream(),true);

    salida.println("Hola, soy el cliente");

    Log.i("Cliente", "Mensaje enviado");

    cliente.close();

    }catch(SocketException e){

        Log.e("ErrorSocket","Error al abrir socket " + e.getMessage());

    } catch (IOException e) {

        Log.e("ErrorSocket","Error al enviar " + e.getMessage());

    }


}

}

我通过以下方法获得 InetAddress:

//The String result param is like: "192.168.0.1&23456"

public InetAddress getInetAddress(String result) {

    InetAddress address = null;

    //5 it an example
    if (result.length() > 5 && result != null) {

        try {

            String[] data = result.split("&");

            Log.i("Data", data[0] + " " + data[1]);

            puerto = Integer.parseInt(data[1]);

            Log.i("PUERTO", "Puerto:" + puerto);

            String ip = data[0];

            Log.i("IP", ip);

            String[] str = ip.split("\\.");

            byte[] IP = new byte[str.length];

            for (int i = 0; i < str.length; i++) {

                IP[i] = (byte) Integer.parseInt(str[i]);
            }

            address = InetAddress.getByAddress(IP);

            Log.i("InetAddress",address.getCanonicalHostName());

        } catch (Exception e) {

            Log.e("Error", "Error al conseguir InnetAddress");

        }

    } else {

        Log.e("Error", "String capturado vacio");

        return address;
    }

    return address;

}

谢谢 :) 这是我的大学期末项目的一个测试项目,一个 GPS 聊天。

编辑:3G nat 打破了这种方式,通过套接字在 2 个设备之间建立 android 连接。我将研究使用 GCM 和另一台服务器的方法。

4

3 回答 3

0

对于您的客户端代码,我发现这对我来说非常有效:

OutputStreamWriter wr = new OutputStreamWriter(cliente.getOutputStream());

然后发送数据使用:

wr.write("DATA TO SEND");
wr.flush();

看起来您正在进行良好的日志记录,我还将添加日志输出行以查看它是否通过了套接字并让它打印出您获得的所有数据。如果所有日志都显示正确的数据但客户端无法连接,请尝试我上面发布的代码,我没有遇到问题。

于 2012-11-10T22:36:29.273 回答
0

交换有关 GPS 位置的信息的更好选择是使用 websocket。我为这种应用程序提供了非常简单的服务器https://github.com/yoman07/geo_server android 演示类,您可以在这里找到https://github.com/yoman07/PhotoShoter/blob/master/PhotoShoterModule/src/main/ java/com/photoshoter/SocketClient.java

于 2014-04-25T19:58:36.203 回答
0

服务器应用程序.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;


public class ServerApp {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){

try {
sock=clientSocket;
InputStreamReader isr=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isr);
} catch (IOException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
 public void run() {
 // TODO Auto-generated method stub
String message;
try {
while((message=reader.readLine())!=null)
{
System.out.println("read :"+message);
tellEveryone(message);
 }
  } catch (IOException e) {
  // TODO Auto-generated catch block
e.printStackTrace();
  }
  }
    private void tellEveryone(String message) {
   // TODO Auto-generated method stub
   Iterator itr=clientOutputStreams.iterator();
 while(itr.hasNext()){
 PrintWriter pWriter=(PrintWriter)itr.next();
 pWriter.println(message);
 pWriter.flush();
  }
  }

  }
   public static void main(String[] args) {
    // TODO Auto-generated method stub

    new ServerApp().createSocket();
  }
   private void createSocket() {
  // TODO Auto-generated method stub
   clientOutputStreams=new ArrayList();
   try {
ServerSocket socket=new ServerSocket(5000);
while(true){
Socket clientSocket=socket.accept();
PrintWriter writer=new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Got a Connection to the Client");
 } 
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}



 Chat Client Source Code
 ===================================================
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;


public class ChatClient {
JTextField outgoing;
JTextArea incoming;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void layOutDesign(){
JFrame frame= new JFrame("Simple Chat Client");
JPanel mainPanel= new JPanel();
 incoming= new JTextArea(15,25);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller=new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing=new JTextField(20);
JButton sendButton=new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setupNetworking();
Thread readerThread=new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setupNetworking() {
// TODO Auto-generated method stub
try {
 sock=new Socket("10.30.10.156", 5000);
 InputStreamReader isR=new InputStreamReader(sock.getInputStream());
 reader=new BufferedReader(isR);
 writer=new PrintWriter(sock.getOutputStream());
  System.out.println("Network Established.");
 } catch (UnknownHostException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
 e.printStackTrace();
 }
}
 public class SendButtonListener implements ActionListener{

 @Override
 public void actionPerformed(ActionEvent ev) {
 // TODO Auto-generated method stub
 try{
 writer.println(outgoing.getText());
 writer.flush();
 }catch (Exception e1) {
  // TODO: handle exception
  e1.printStackTrace();
  }

  outgoing.setText("");
  outgoing.requestFocus();
 }

 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  new ChatClient().layOutDesign();
  }
 public class IncomingReader implements Runnable{

  String message;
  @Override
   public void run() {
  // TODO Auto-generated method stub
  try {
  while((message=reader.readLine())!=null){
  System.out.println("Read :"+message);
   incoming.append(message+"\n");
  }
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }

  }
  }

转到服务器代码...并更改系统的 IP,然后连接到客户端

并享受网络中同事之间的聊天......

于 2013-06-19T11:51:10.227 回答