私はNodejsとソケットプログラミングを使用してチャットアプリケーションを実装しています。 Androidアプリケーションからメッセージを送信すると、WebStormの端末に接続された状態で表示されるはずですが、何も起こっていません。Androidアプリがソケットを使用してローカルホストサーバにメッセージを送信しない
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
})
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('message',function(data){
var sockets = io.sockets.sockets;
// sockets.forEach(function(sock){
// if(sock.id != socket.id)
// {
// sock.emit('message',data);
// }
// })
socket.broadcast.emit('message', data);
console.log('message '+data);
})
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
})
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})
index.htmlを
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
<h1>Hello Sockets</h1>
</html>
ChatFragment.java
package com.example.admin.chatapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ChatFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ChatFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ChatFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private EditText mInputMessageView;
private RecyclerView mMessagesView;
private OnFragmentInteractionListener mListener;
private List<Message> mMessages = new ArrayList<Message>();
private RecyclerView.Adapter mAdapter;
private Socket socket;
{
try{
socket = IO.socket("http://192.168.x.x:3000");
}catch(URISyntaxException e){
throw new RuntimeException(e);
}
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ChatFragment.
*/
// TODO: Rename and change types and number of parameters
public static ChatFragment newInstance(String param1, String param2) {
ChatFragment fragment = new ChatFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public ChatFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
socket.connect();
socket.on("message", handleIncomingMessages);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chat, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
mAdapter = new MessageAdapter(mMessages);
/*try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}*/
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMessagesView = (RecyclerView) view.findViewById(R.id.messages);
mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesView.setAdapter(mAdapter);
ImageButton sendButton = (ImageButton) view.findViewById(R.id.send_button);
mInputMessageView = (EditText) view.findViewById(R.id.message_input);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}
private void sendMessage(){
String message = mInputMessageView.getText().toString().trim();
mInputMessageView.setText("");
addMessage(message);
JSONObject sendText = new JSONObject();
try{
sendText.put("text",message);
socket.emit("message", sendText);
}catch(JSONException e){
}
}
public void sendImage(String path)
{
JSONObject sendData = new JSONObject();
try{
sendData.put("image", encodeImage(path));
Bitmap bmp = decodeImage(sendData.getString("image"));
addImage(bmp);
socket.emit("message",sendData);
}catch(JSONException e){
}
}
private void addMessage(String message) {
mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
.message(message).build());
// mAdapter = new MessageAdapter(mMessages);
mAdapter = new MessageAdapter(mMessages);
mAdapter.notifyItemInserted(0);
scrollToBottom();
}
private void addImage(Bitmap bmp){
mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
.image(bmp).build());
mAdapter = new MessageAdapter(mMessages);
mAdapter.notifyItemInserted(0);
scrollToBottom();
}
private void scrollToBottom() {
mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
}
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
private Bitmap decodeImage(String data)
{
byte[] b = Base64.decode(data,Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
return bmp;
}
private Emitter.Listener handleIncomingMessages = new Emitter.Listener(){
@Override
public void call(final Object... args){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("cdcdc", String.valueOf(args[0]));
JSONObject data = (JSONObject) args[0];
Log.d("cdcdc", String.valueOf(data));
String message;
String imageText;
try {
message = data.getString("text").toString();
addMessage(message);
} catch (JSONException e) {
// return;
}
try {
imageText = data.getString("image");
addImage(decodeImage(imageText));
} catch (JSONException e) {
//retur
}
}
});
}
};
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
@Override
public void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
INDEを実行するにはWebStormでx.jsファイルには、私はコマンドを私にポート3000
に聞いて
サーバーとして出力を与える
index.js
ノードを入力します私のアプリからメッセージを送ると何も起こりません。端末はそのままです。私は何をすべきか、これを引き起こす原因は何か。 27:52.578 23204から23204/com.example.admin
更新 私はngrokを使用し
socket = IO.socket("http://01e42de0.ngrok.io");
に自分のアンドロイドのコードを変更するには、私にエラー
06-05 20を与えます.chatapp E/AndroidRuntime:致命的除外:メイン
プロセス:com.example.admin.chatapp、PID:23204 java.lang.RuntimeException:アクティビティを開始できません ComponentInfo {com.example.admin.chatapp/com.example.admin.chatapp.SocketActivity}: android.view.InflateException:バイナリXMLファイル行#9:バイナリXML ファイルの行#9:エラー膨張クラスフラグメント android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2728)で android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)で android.app.ActivityThreadで。-wrap12(ActivityThread.java) at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1527) android.os.Handler.dispatchMessage(Handler.java:102) とandroid.os.Looper.loop(Looper.java:154) とandroid.app.ActivityThread.main(ActivityThread.java:6290) でのjava com.android.internal.os.ZygoteInit.mainで.lang.reflect.Method.invoke(ネイティブメソッド) でcom.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886) (ZygoteInit 。Java:776) 原因:android.view.InflateException:バイナリXMLファイル行#9: バイナリXMLファイル行#9:クラスフラグメントを拡張するエラー 原因:android.view.InflateException:バイナリXMLファイル行#9: java.lang.RuntimeException:java.net.URISyntaxException:インデックス0のスキーム名で 不正な文字:http://01e42de0.ngrok.io com.example.admin.chatapp.ChatFragmentで (ChatFragment.java:64によって引き起こさクラスフラグメント を膨らま エラー) at java.lang.Class.newInstance(ネイティブメソッド) android.app.Fragment.instantiate(Fragment.java:622) a android.app.FragmentController.onCreateView(FragmentController.java:98)におけるT android.app.Fragment.instantiate android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)で(Fragment.java:593) android.app.Activity.onCreateViewで(Activity.java:5982) でandroid.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36) android.support.v4.app.FragmentActivity.onCreateViewで(FragmentActivity.java:79) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)012 android.view.LayoutInflater.rInflateChildrenでandroid.view.LayoutInflater.rInflate(LayoutInflater.java:858) でandroid.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727) で(LayoutInflater.java:821) android.view.LayoutInflater.inflateでandroid.view.LayoutInflater.inflate(LayoutInflater.java:426) でandroid.view.LayoutInflater.inflate(LayoutInflater.java:518) (LayoutInflater.java:377) でで android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) android.app.Activity.performCreateで com.example.admin.chatapp.SocketActivity.onCreate(SocketActivity.java:22)で android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) で(Activity.java:6760) でandroid.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) でandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2681) android.app.ActivityThreadました。 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 android.os.Looper.loopでandroid.os.Handler.dispatchMessageでandroid.app.ActivityThread $ H.handleMessage(ActivityThread.java:1527) (Handler.java:102) (Looper.java:154で com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInitでjava.lang.reflect.Method.invoke(ネイティブメソッド) でandroid.app.ActivityThread.main(ActivityThread.java:6290) で) .java:886) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 原因:java.net。URISyntaxException:java.net.URI $ Parser.checkCharsでjava.net.URI $ Parser.fail(URI.java:2856) でhttp://01e42de0.ngrok.io (URI.java:3029) :インデックス0のスキーム 名に不正な文字java.net.URI $ Parser.checkChar(URI.java:3039) at java.net.URI $ Parser.parse(URI.java:3055) (java.net.URI)(URI.java:590) (IO.java:41) io.socket.client.IO.socket(IO.java:41) io.socket.client.IO.socket(IO.java:37) (com.example.admin.chatapp.ChatFragment)(ChatFragment .java:61) at java.lang.Class.newInstance(ネイティブM ethod) android.app.FragmentManagerImpl.onCreateViewでandroid.app.Fragment.instantiateでandroid.app.Fragment.instantiate(Fragment.java:622) (Fragment.java:593) (FragmentManager.java:2302で android.app.Activity.onCreateViewで) でandroid.app.FragmentController.onCreateView(FragmentController.java:98) (Activity.java:5982) android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycombで.java:36) at android.support.v4.app.FragmentActivity.onCreateView(Fragme ntActivity.java:79) でandroid.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777) android.view.LayoutInflater.rInflateでandroid.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727) (AT android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)android.view.LayoutInflater.inflate(LayoutInflater.java:518で )android.view.LayoutInflater.inflateで でLayoutInflater.java:858) (LayoutInflater .java:426) android.view.LayoutInflater.inflate(LayoutInflater.java:377) でandroid.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) でandroid.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) com.example.adminで アンドロイドで.chatapp.SocketActivity.onCreate android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)で(SocketActivity.java:22)android.app.Activity.performCreate(Activity.java:6760)で アクティビティandroid.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814) android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1527)でandroid.app.ActivityThread.-wrap12(ActivityThread.java) で android.os.Handler.dispatchMessage(Handler.java:102) とandroid.os.Looper.loop(Looper.java:154) とandroid.app.ActivityThread.main(ActivityThread.java:6290) でのjava .lang.reflect.Method.invoke(ネイティブメソッド) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886) comで。android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
URL 'HTTPです://192.168.1.9:3000'あなたのAndroidデバイスによって可視? –
@MarcosPlaconaどうすればいいですか? –
あなたのアンドロイドデバイスのネットワーク/無線LAN設定に入り、あなたのIPアドレスが –