使用套接字的简单客户端 - 服务器应用

时间:2016-12-02 12:24:39

标签: android scala sockets client-server

我在“Hello world”客户端/服务器应用程序上工作,我正在努力解决服务器之间的连接,该连接是用 scala <编写的/ strong>并在我的PC和客户端上运行,该文件以 android 编写并在我的手机上运行。

我连接了同一子网上的两个应用程序,即。我的路由器并为它们设置相应的IP和端口。   问题是用Android编写的客户端会立即停止。

P.S。出于安全原因,我没有发布我的IP地址。

服务器代码是:

import java.net._
import java.io._
import scala.io._

object MyServer extends App
{
    try
    {
       val server = new ServerSocket(4242)
       println("Serve initialized:")
       val client = server.accept

       val in = new BufferedReader(new InputStreamReader(client.getInputStream()))
       val out = new PrintStream(client.getOutputStream())
       var message =in.readLine()
       while(message != null)
        {
         println("Server received:" + message)
         out.println("Message received")
         out.flush
         if (message.equals("Disconnect")) 
          {
            client.close; 
            server.close;
            println("Server closing:")
          }
          message= in.readLine()
         }
    }

    catch 
    {
       case e: Exception => println(e.getStackTrace); System.exit(1)
    }
}

客户端代码是:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.ghiurutan.clientv1.MainActivity">

    <Button
        android:text="@string/button_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="158dp" />

    <TextView
        android:text="@string/text_view_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/editText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/textView"
        android:layout_alignBottom="@+id/editText"
        android:layout_toLeftOf="@+id/button"
        android:layout_toStartOf="@+id/button" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText"
        android:layout_marginBottom="125dp"
        android:layout_alignBottom="@+id/button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ghiurutan.clientv1">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.example.ghiurutan.clientv1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import android.view.View;
import android.widget.*;



public class MainActivity extends AppCompatActivity {
    private Socket socket;
    private static final int SERVER_PORT=4242;
    private static final String SERVER_IP="";
    private EditText editText;
    private Button button;
    private PrintWriter printWriter;
    private String messageToSend;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(
                new Runnable()
                {
                    public void run()
                    {
                        try{
                            socket=new Socket(InetAddress.getByName(SERVER_IP),SERVER_PORT);
                        }catch(UnknownHostException e)
                        {
                            System.out.println(e.getLocalizedMessage());
                        }catch(IOException e)
                        {
                            System.out.println(e.getLocalizedMessage());
                        }
                    }
                }
        ).start();

    }

    @Override
    protected void onStart()
    {
        super.onStart();

        try{
            printWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        }catch(UnknownHostException e)
        {
            System.out.println(e.getLocalizedMessage());
        }catch(IOException e)
        {
            System.out.println(e.getLocalizedMessage());
        }

        editText=(EditText)findViewById(R.id.editText);
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(
              new Button.OnClickListener()
              {
                  public void onClick(View v)
                  {
                      messageToSend=editText.getText().toString();
                      editText.setText("");
                      printWriter.println(messageToSend);
                  }
              }
        );
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
}

我必须提到我只是编程的初学者,所以欢迎任何帮助或建议。     在这种情况下我应该使用端口转发吗?有人告诉我,将服务器放在云端是个好主意,因为这样会更加明显。

1 个答案:

答案 0 :(得分:1)

实际可行的最终代码如下:

package com.example.ghiurutan.clientv1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import android.view.View;
import android.widget.*;



public class MainActivity extends AppCompatActivity {
    private Socket socket;
    private static final int SERVER_PORT=8888;
    private static final String SERVER_IP="192.168.100.2";
    private EditText currentEditText,destinationEditText;
    private TextView resultTextView;
    private Button button;
    private PrintWriter printWriter;
    private BufferedReader bufferedReader;
    private String currentLocationMessage,
    destinationLocationMessage,messageReceived;

//Called when the activity is first created
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        button=(Button)findViewById(R.id.button);
        currentEditText=(EditText)findViewById(R.id.editText1);
        destinationEditText=(EditText)findViewById(R.id.editText2);
        resultTextView=(TextView)findViewById(R.id.textView4);


        button.setOnClickListener(
                    new Button.OnClickListener() {
                    public void onClick(View v) {

                        currentLocationMessage = currentEditText.getText().toString();
                        destinationLocationMessage=destinationEditText.getText().toString();
                        currentEditText.setText("");
                        destinationEditText.setText("");
                        new Thread(new SendMessage()).start();
                    }
                }
        );
    }


    private class SendMessage implements Runnable {
        public void run() {
            try {
                String inputMessage=currentLocationMessage+"#"+destinationLocationMessage;
                socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT);
                printWriter = new PrintWriter(socket.getOutputStream());
                bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                printWriter.println(inputMessage);
                printWriter.flush();
                currentLocationMessage="";
                destinationLocationMessage="";
                messageReceived = bufferedReader.readLine();

               runOnUiThread(new Runnable(){
                   @Override
                   public void run()
                   {
                       if(messageReceived==null || messageReceived.equals(""))
                       {
                           resultTextView.setText("Error.Please check the inputs.");
                       }else {
                           resultTextView.setText(messageReceived);
                       }
                   }
               });
                printWriter.close();
                bufferedReader.close();
                socket.close();

            } catch (UnknownHostException e) {
                System.out.println(e.getLocalizedMessage());
            } catch (IOException e) {
                System.out.println(e.getLocalizedMessage());
            }
        }

    }


//Called when the activity is about to become visible
    @Override
    protected void onStart()
    {
        super.onStart();
    }

    //Called when the activity has become visible
    @Override
    protected void onResume()
    {
        super.onResume();
    }

    //Called when another activity is taking focus
    @Override
    protected void onPause()
    {
        super.onPause();
    }

    //Called before the activity is destroyed
    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
}