Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Mobile > Mobile Forum > Android - TCP Client ส่งข้อมูลไปที่ Server ได้แล้วแต่อยากใหม่สามารถรับข้อมูลกลับมาได้คับผม



 

Android - TCP Client ส่งข้อมูลไปที่ Server ได้แล้วแต่อยากใหม่สามารถรับข้อมูลกลับมาได้คับผม

 



Topic : 117178



โพสกระทู้ ( 3 )
บทความ ( 0 )



สถานะออฟไลน์




คือผมได้ทดลองการเขียนตัวTcp client ขึ้นมาครับ ต้องการให้มันสามารถส่งค่าไปที่ Server แล้วรอค่าจาก Server กลับมาคับ ตัวServerที่ใช้เป็นโปรแกรมที่ชื่อว่า Herculesคับ ผททดสองเขียนจนมันสามารถส่งข้อความไปยังServerได้โดยกดปุ่มSent จะส่งข้อความเป็นคำว่า Submitไป พอส่งเสร็จก็จะรอรับค่าจากServerกลับมา(กดเองจากโปรแกรม Hercules) แต่ผมยังมองไม่เห็นทางที่จะเขียนรับข้อมูลกลับมาเลย

อันนี้เป็นส่วน MainActivity คับ
Code (Android-Java)
package com.testt;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.AsyncTask;
import android.util.Log;
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.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

public class MainActivity extends Activity {
   
    // Used to reference UI elements of main.xml
    private TextView text,serverResponse;
    private EditText ipBox;
    private EditText portBox;
    private ToggleButton connect;
    private Button send;
	private static final String TAG = "CClient"; 
    private String ipAddress;
    private Socket client;
    private DataOutputStream outToServer;
    private DataInputStream inFromServer;
    private boolean connected = false;   
    private final int START = 0xffffff;
    private final int msgBoxHint = START;
    private final int appendText = START + 1;
	final String welcomeMsg = "Hii";
	Toast mytoast , savetoast;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Log.d(TAG, "Here 1");
        ipAddress = getLocalIpAddress();
        Log.d(TAG, "Get local IP="+ ipAddress);
        text = (TextView) findViewById(R.id.text);
        ipBox =  (EditText) findViewById(R.id.ipBox);
        serverResponse = (TextView) findViewById(R.id.response);
        portBox =  (EditText) findViewById(R.id.portBox);
        send = (Button) findViewById(R.id.send);
        send.setOnClickListener(buttonsendOnClickListener);      
        connect = (ToggleButton) findViewById(R.id.connect);      
        connect.setOnClickListener(buttonConnectOnClickListener);
    	Button buttonExit = (Button) findViewById(R.id.btnExit);
    	buttonExit.setOnClickListener(new View.OnClickListener() {
    	    public void onClick(View v) {
    			Log.d(TAG, "Exit");
                Log.d(TAG, "Disconnect" );
                if(client != null)
                {
                    try {
                        client.close();
                    } catch (IOException e) {
                   	 Log.d(TAG, "Disconnect"+e.toString() );
                    }
                } 
                finish();
    	    }
    	});  
    }

	OnClickListener buttonConnectOnClickListener = new OnClickListener() {    
    /** Manages all button clicks from the screen */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
	public void onClick(View arg0) {
        switch(arg0.getId())
        {
            case R.id.connect:
                 if(connect.isChecked())
                 {
                	 Log.d(TAG, "Connect" );
 			         
                     EditText edIP = (EditText) findViewById(R.id.ipBox);
 			         String ed_textIP = edIP.getText().toString().trim();
 			         if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null  )
 			         {
 			    	    Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
 			    	   Log.d(TAG, "IP Address or PORT is incorrect");
 			         }
			            setValues(R.id.connect,true);
			            setValues(R.id.send,true);
			            setValues(R.id.ipBox,false);
 					String tMsg = welcomeMsg.toString();
 					MyClientTask myClientTask = new MyClientTask(ipBox
 							.getText().toString(), Integer.parseInt(portBox
 							.getText().toString()),
 							tMsg);
 					
 					
 					if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
 						myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 					else
 						myClientTask.execute();
                 }
                 else
                 { /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
                     Log.d(TAG, "Disconnect" );
                     if(client != null)
                     {
                         try {
                             client.close();
                         } catch (IOException e) {
                        	 Log.d(TAG, "Disconnect"+e.toString() );
                         }
                        
                         setText(R.id.text,"Press the connect button to start the client");
                         setText(msgBoxHint,"");
                        
                         setValues(R.id.connect,false);
                         setValues(R.id.ipBox,true);
                         setValues(R.id.send,false);
                     }   
                     else
                     {
                         setValues(R.id.connect,false);
                     }
                 }
                 break;
        }
    }
	}; 
	
	public class MyClientTask extends AsyncTask<Void, Void, Void> {

		String dstAddress;
		int dstPort;
		String response = "";
		String msgToServer;
		MyClientTask(String addr, int port, String msgTo) {
			dstAddress = addr;
			dstPort = port;
			msgToServer = msgTo;
		}
		
		protected Void doInBackground(Void... arg0) {
			Log.d(TAG, "InBackground");
			Socket socket = null;
			DataOutputStream dataOutputStream = null;
			DataInputStream dataInputStream = null;
			
			try {
				client  = new Socket(dstAddress, dstPort);
		        outToServer = new DataOutputStream(client.getOutputStream());		
		        inFromServer = 	new DataInputStream(new BufferedInputStream(client.getInputStream()));	// Input stream <- from server
			}catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				Log.d(TAG, "InBackground 1");
				e.printStackTrace();
				response = "UnknownHostException: " + e.toString();
				MainActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						mytoast =  Toast.makeText(MainActivity.this, "Error UnknownHostException", 
							Toast.LENGTH_SHORT);
							mytoast.show();
							setValues(R.id.send,false);
						    Handler handler = new Handler();
					        handler.postDelayed(new Runnable() {
					           @Override
					           public void run() {
					        	   mytoast.cancel(); 
					           }
					    }, 500);					  
					}
				});
			} catch (IOException e) {
				Log.d(TAG, "InBackground 2");
				// TODO Auto-generated catch block
				e.printStackTrace();
				response = "IOException: " + e.toString();
				MainActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						mytoast =  Toast.makeText(MainActivity.this, "Error IOException", 
							Toast.LENGTH_SHORT);
							mytoast.show();
							setValues(R.id.connect,false);
							setValues(R.id.send,false);
						    Handler handler = new Handler();
					        handler.postDelayed(new Runnable() {
					           @Override
					           public void run() {
					        	   mytoast.cancel(); 
					           }
					    }, 500);
						  
					}
				});
			}finally {
				Log.d(TAG, "InBackground 3");
				if (socket != null) {
					try {
						socket.close();
						Log.d(TAG, "InBackground 3.11");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Log.d(TAG, "InBackground 3.12");
					}
				}
				Log.d(TAG, "InBackground 3.1");
			}
			Log.d(TAG, "InBackground 4");
			return null;		
		}
		@Override
		protected void onPostExecute(Void result) {
			serverResponse.setText(response);
			super.onPostExecute(result);
		}
	}
	
	OnClickListener buttonsendOnClickListener = new OnClickListener() {    
	    /** Manages all button clicks from the screen */
		@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
		public void onClick(View arg0) {
	        switch(arg0.getId())
	        {
	            case R.id.send:
	                	 Log.d(TAG, "Sent" );
	                	 String sentence = "Submit";
	                	 String recieve = "";
	                	 serverResponse  = (TextView) findViewById(R.id.response);
	                     try {
		                	 Log.d(TAG, "Sent 1-1" );	  
	         				if(sentence != null){
	         					outToServer.writeUTF(sentence);
	         					outToServer.flush();	
	        				}
	         				Log.d(TAG, "Sent 1-2" );	
	
	         				/*
	         				 * 
	         				 * 
	         				 * 
	         				 * 
	         				 * 
	         				 */
		         				
	         								
	                     } catch (IOException e) {
	                         setValues(R.id.ipBox,true);
	                         setValues(R.id.connect,false);
	                         setValues(R.id.send,false);
	                     }
	                     break;
	        }
	      }
		}; 
 
    private String getLocalIpAddress() {
        Log.d(TAG, "Here 2");
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        Log.d(TAG, "Here 3");
        WifiInfo info = wifi.getConnectionInfo();
        Log.d(TAG, "Here 4");
        return Formatter.formatIpAddress(info.getIpAddress());
    }
    
    private void setText(int view, String content)
    {
        switch(view)
        {
            case R.id.ipBox: ipBox.setText(content); break;
            case R.id.text: text.setText(content+"\n\n"); break;
            case appendText: text.append(content+"\n\n"); break;
        }
    }
   
    private void setValues(int view, boolean value)
    {
        switch(view)
        {
            case R.id.ipBox: ipBox.setEnabled(value); break;
            case R.id.send: send.setEnabled(value); break;
            case R.id.connect: connect.setChecked(value); break;
        }
    }
    
}



ผมคิดว่ามันจะต้องมาเขียนในช่วง /****/ แต่ยังไม่สามารถเขียนออกมาได้เลยอยากขอคำแนะนำหน่อยคับ



Tag : Mobile, Android, JAVA, Mobile









ประวัติการแก้ไข
2015-06-15 20:14:49
Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2015-06-15 20:13:04 By : upgrade9909 View : 2201 Reply : 0
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : Android - TCP Client ส่งข้อมูลไปที่ Server ได้แล้วแต่อยากใหม่สามารถรับข้อมูลกลับมาได้คับผม
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 03
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่