336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android onTouch 에서 ACTION_DOWN 만 들어올경우


ImageView 위에서 터치를 입력 받을 경우


ImageView 에



ImageView imageView = (ImageView) findViewById(R.id.imageView);

imageView.setClickable(true);


Clickable 을 True 로 해주어야 MOVE 나 DOWN 이벤트가 캐치된다.

'Programming > Android' 카테고리의 다른 글

android-screenshot-library  (0) 2013.11.06
Android 졸업 작품 도움 요청 카페  (0) 2013.10.22
Android 실습 0823  (0) 2013.08.23
PinchToZoom ImageView 로 구현  (0) 2013.08.23
Android 채팅 소스 05  (1) 2013.08.21

JAVA JTable 실습 예제

Programming/JAVA,JSP 2013. 8. 24. 12:07 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tansanc.tistory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

class Info
{
	public String title;
	public String publisher;
	public String year;
	public int price;
	public long contentLength = 0L;

	public Info(String title, String publisher, String year, int price)
	{
		this.title = title;
		this.publisher = publisher;
		this.year = year;
		this.price = price;
	}
}

class InfoTableModel extends AbstractTableModel
{
	private static final long serialVersionUID = 7932826462497464190L;
	public ArrayList pages;

	public InfoTableModel()
	{
		pages = new ArrayList();
	}

	public int getColumnCount()
	{
		return 4;
	}

	public int getRowCount()
	{
		return pages.size();
	}

	public void addInfo(Info page)
	{
		int idx = pages.size();
		pages.add(page);
		fireTableRowsInserted(idx, idx); // 반드시 호출해야한다.
	}

	public Object getValueAt(int rowIndex, int columnIndex)
	{
		Info info = pages.get(rowIndex);
		switch (columnIndex)
		{
		case 0:
			return info.title;
		case 1:
			return info.publisher;
		case 2:
			return info.year;
		case 3:
			return info.price;
		case 4:
			return info.contentLength;
		default:
			return "invalid";
		}
	}
}

class myFrame extends JFrame
{
	JTable table;

	public myFrame()
	{
		// TODO Auto-generated constructor stub
		setSize(600, 400);
		setVisible(true);

		InfoTableModel model = new InfoTableModel();
		TableColumnModel columnModel = new DefaultTableColumnModel();
		TableCellRenderer renderer = new DefaultTableCellRenderer(); // 기본구현
		model.addInfo(new Info("1", "1", "1", 50000));

		try
		{
			Connection con = ConnectDatabase.makeConnection();
			Statement stmt;
			stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM books");
			while (rs.next())
			{
				int book_id = rs.getInt("book_id");
				String title = rs.getString("title");
				String publisher = rs.getString("publisher");
				String year = rs.getString("year");
				int price = rs.getInt("price");
				System.out.println(title + publisher + year + price);
				model.addInfo(new Info(title, publisher, year, price));
			}

		} catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("done");
		TableColumn column = new TableColumn(0);
		column.setCellRenderer(renderer); // 이렇게 하지 않아도 알아서 제공된다.
		column.setHeaderValue("title");
		columnModel.addColumn(column);

		column = new TableColumn(1);
		column.setHeaderValue("publisher");
		columnModel.addColumn(column);

		column = new TableColumn(2);
		column.setHeaderValue("year");
		columnModel.addColumn(column);

		column = new TableColumn(3);
		column.setHeaderValue("price");
		columnModel.addColumn(column);

		table = new JTable(model, columnModel);
		add(table);
	}

}

public class ConnectDatabase
{
	public static Connection makeConnection()
	{
		String url = "jdbc:mysql://localhost/book_db";
		String id = "root";
		String password = "root";
		Connection con = null;
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("드라이버 적재 성공");
			con = DriverManager.getConnection(url, id, password);
			System.out.println("데이터베이스 연결 성공");
		} catch (ClassNotFoundException e)
		{
			System.out.println("드라이버를 찾을 수 없습니다.");
		} catch (SQLException e)
		{
			System.out.println("연결에 실패하였습니다.");
		}
		return con;
	}

	public static void main(String[] args)
	{
		makeConnection();
		new myFrame();
	}
}


'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 소수를 판단하는 GUI 프로그램  (0) 2013.12.21
JAVA 버블 정렬  (0) 2013.11.30
JAVA 채팅 프로그램 소스  (0) 2013.08.23
JAVA 채팅 클라이언트  (0) 2013.08.23
JAVA 계산기 프로그램 부분완성  (0) 2013.08.16

Android 실습 0823

Programming/Android 2013. 8. 23. 17:57 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

activity_find.xml

 

activity_main.xml

 

activity_register.xml

 

 

package com.tistory.tansanc.Test130805;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

public class MainActivity extends Activity {
	// Introduce an delay
	private final int WAIT_TIME = 2500;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				// Simulating a long running task
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				/* Create an Intent that will start the ProfileData-Activity. */

				SharedPreferences pref = getSharedPreferences("SaveState", 0);
				float Latitude = pref.getFloat("Latitude", (float) 0.0);
				if (Latitude == 0.0) {
					Intent mainIntent = new Intent(MainActivity.this,
							RegisterActivity.class);
					MainActivity.this.startActivity(mainIntent);
					MainActivity.this.finish();
				}
				else
				{
					Intent mainIntent = new Intent(MainActivity.this,
							FindActivity.class);
					MainActivity.this.startActivity(mainIntent);
					MainActivity.this.finish();
				}
			}
		}, WAIT_TIME);
	}
}
package com.tistory.tansanc.Test130805;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelXorXfermode;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

public class FindActivity extends Activity {
	FrameLayout fl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_find);
		SharedPreferences pref = getSharedPreferences("SaveState", 0);
		float Latitude = pref.getFloat("Latitude", (float) 0.0);
		float Longitude = pref.getFloat("Longitude", (float) 0.0);
		float Altitude = pref.getFloat("Altitude", (float) 0.0);

		String sloc = String.format("위도:%f\n경도:%f\n고도:%f", Latitude, Longitude,
				Altitude);

		TextView destinationLocation = (TextView) findViewById(R.id.destinationLocation);
		destinationLocation.setText(sloc);

		fl = (FrameLayout) findViewById(R.id.fl);
		RadarView rv = new RadarView(this);
		fl.addView(rv);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.find, menu);
		return true;
	}
	boolean clock = false;

	class RadarView extends View {

		Handler mHandler = new Handler(){
			public void handleMessage(android.os.Message msg) {
				clock = !clock;
				invalidate();
				sendEmptyMessageDelayed(0, 500);
			};
		};
		
		public RadarView(Context context) {
			super(context);
			mHandler.sendEmptyMessageDelayed(0, 500);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			Paint Pnt = new Paint();
			Pnt.setAntiAlias(true);

			if(clock)
			{
				Pnt.setColor(Color.RED);
			}
			else
			{
				Pnt.setColor(Color.WHITE);				
			}
			canvas.drawCircle(canvas.getWidth()/2, canvas.getHeight()/2, 80, Pnt);

			Pnt.setXfermode(new PixelXorXfermode(Color.BLACK));

			Pnt.setColor(Color.BLUE);
			canvas.drawRect(100, 100, 200, 200, Pnt);
			super.onDraw(canvas);
		}
	}

}

package com.tistory.tansanc.Test130805;

import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class RegisterActivity extends Activity {
	LocationManager mLocMan;
	String mProvider;
	TextView locationText;

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

		mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mProvider = mLocMan.getBestProvider(new Criteria(), true);

		locationText = (TextView) findViewById(R.id.location);
	}

	public void onResume() {
		super.onResume();
		mLocMan.requestLocationUpdates(mProvider, 3000, 10, mListener);
	}

	public void mOnClick(View v) {
		SharedPreferences pref = getSharedPreferences("SaveState", 0);
		SharedPreferences.Editor edit = pref.edit();
		edit.putFloat("Latitude", Latitude);
		edit.putFloat("Longitude", Longitude);
		edit.putFloat("Altitude", Altitude);
		edit.commit();
	}

	float Latitude;
	float Longitude;
	float Altitude;
	LocationListener mListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			String sloc = String.format("위도:%f\n경도:%f\n고도:%f",
					location.getLatitude(), location.getLongitude(),
					location.getAltitude());

			Latitude = (float) location.getLatitude();
			Longitude = (float) location.getLongitude();
			Altitude = (float) location.getAltitude();
			locationText.setText(sloc);
		}

		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register, menu);
		return true;
	}

}

PinchToZoom ImageView 로 구현

Programming/Android 2013. 8. 23. 15:42 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc.Test130805;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class ImgViewTouch extends ImageView {

	private static final String TAG = "ImgViewChild";
	private static final boolean D = false;

	private Matrix matrix;
	private Matrix savedMatrix;
	private Matrix savedMatrix2;

	private Drawable d;

	private static final int NONE = 0;
	private static final int DRAG = 1;
	private static final int ZOOM = 2;
	private int mode = NONE;

	private PointF start = new PointF();
	private PointF mid = new PointF();
	private float oldDist = 1f;

	private static final int WIDTH = 0;
	private static final int HEIGHT = 1;

	private boolean isInit = false;

	/** Constants describing the state of this imageview */
	private boolean isMoving;
	private boolean isScaling;
	private boolean isRestoring;

	public ImgViewTouch(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setScaleType(ScaleType.MATRIX);
		matrix = new Matrix();
		savedMatrix = new Matrix();
		savedMatrix2 = new Matrix();
	}

	public ImgViewTouch(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ImgViewTouch(Context context) {
		this(context, null);
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		if (D)
			Log.i(TAG, "onLayout");
		d = this.getDrawable();
		super.onLayout(changed, left, top, right, bottom);
		if (isInit == false) {
			init();
			isInit = true;
		}
	}

	@Override
	public void setImageBitmap(Bitmap bm) {
		if (D)
			Log.i(TAG, "setImageBitmap");
		super.setImageBitmap(bm);
		isInit = false;
		init();
	}

	@Override
	public void setImageResource(int resId) {
		if (D)
			Log.i(TAG, "setImageResource");
		super.setImageResource(resId);
		d = getDrawable();
		isInit = false;
		init();
	}

	protected void init() {
		d = this.getDrawable();
		initImgPos();
		setImageMatrix(matrix);
	}

	/**
	 * Sets the image in the imageview using the matrix
	 */
	public void initImgPos() {

		float[] value = new float[9];
		this.matrix.getValues(value);

		int width = this.getWidth();
		int height = this.getHeight();

		if (d == null)
			return;
		int imageWidth = d.getIntrinsicWidth();
		int imageHeight = d.getIntrinsicHeight();
		int scaleWidth = (int) (imageWidth * value[0]);
		int scaleHeight = (int) (imageHeight * value[4]);

		if (imageWidth > width || imageHeight > height) {

			float xratio = (float) width / (float) imageWidth;
			float yratio = (float) height / (float) imageHeight;

			// Math.min fits the image to the shorter axis. (with letterboxes
			// around)
			// Math.max fits the image th the longer axis. (with the other axis
			// cropped)
			value[0] = value[4] = Math.max(xratio, yratio);
		}

		scaleWidth = (int) (imageWidth * value[0]);
		scaleHeight = (int) (imageHeight * value[4]);

		// align the image to the top left corner
		value[2] = 0;
		value[5] = 0;

		// center the image. it will be aligned to the top left corner
		// otherwise.
		value[2] = (float) width / 2 - (float) scaleWidth / 2;
		value[5] = (float) height / 2 - (float) scaleHeight / 2;

		matrix.setValues(value);
		setImageMatrix(matrix);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		if (D)
			dumpEvent(event);

		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			savedMatrix.set(matrix);
			start.set(event.getX(), event.getY());
			mode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			oldDist = spacing(event);
			if (oldDist > 10f) {
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_UP:

		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			restore(matrix);
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) {
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY()
						- start.y);

			} else if (mode == ZOOM) {
				float newDist = spacing(event);
				if (newDist > 10f) {
					matrix.set(savedMatrix);
					float scale = newDist / oldDist;
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}

		// Matrix value modification
		// comment out below 2 lines to remove all restrictions on image
		// transformation.
		matrixTuning(matrix);
		setImageMatrix(savedMatrix2);

		return true;
	}

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	private void matrixTuning(Matrix matrix) {
		float[] value = new float[9];
		matrix.getValues(value);
		float[] savedValue = new float[9];
		savedMatrix2.getValues(savedValue);

		int width = getWidth();
		int height = getHeight();

		Drawable d = getDrawable();
		if (d == null)
			return;
		int imageWidth = d.getIntrinsicWidth();
		int imageHeight = d.getIntrinsicHeight();
		int scaleWidth = (int) (imageWidth * value[0]);
		int scaleHeight = (int) (imageHeight * value[4]);

		// don't let the image go outside
		if (value[2] < width - scaleWidth)
			value[2] = width - scaleWidth;
		if (value[5] < height - scaleHeight)
			value[5] = height - scaleHeight;
		if (value[2] > 0)
			value[2] = 0;
		if (value[5] > 0)
			value[5] = 0;

		// maximum zoom ratio: 2x
		if (value[0] > 2 || value[4] > 2) {
			value[0] = savedValue[0];
			value[4] = savedValue[4];
			value[2] = savedValue[2];
			value[5] = savedValue[5];
		}

		// don't let the image become smaller than the screen
		if (imageWidth > width || imageHeight > height) {
			if (scaleWidth < width && scaleHeight < height) {
				int target = WIDTH;
				if (imageWidth < imageHeight)
					target = HEIGHT;

				if (target == WIDTH)
					value[0] = value[4] = (float) width / imageWidth;
				if (target == HEIGHT)
					value[0] = value[4] = (float) height / imageHeight;

				scaleWidth = (int) (imageWidth * value[0]);
				scaleHeight = (int) (imageHeight * value[4]);

				if (scaleWidth > width)
					value[0] = value[4] = (float) width / imageWidth;
				if (scaleHeight > height)
					value[0] = value[4] = (float) height / imageHeight;
			}
		}

		// don't allow scale down under its size
		else {
			if (value[0] < 1)
				value[0] = 1;
			if (value[4] < 1)
				value[4] = 1;
		}

		// center the image
		scaleWidth = (int) (imageWidth * value[0]);
		scaleHeight = (int) (imageHeight * value[4]);
		if (scaleWidth < width) {
			value[2] = (float) width / 2 - (float) scaleWidth / 2;
		}
		if (scaleHeight < height) {
			value[5] = (float) height / 2 - (float) scaleHeight / 2;
		}

		matrix.setValues(value);
		savedMatrix2.set(matrix);
	}

	/**
	 * Gives animation effect after touchscreen event, puts the image back into
	 * the screen, limits max zoom at specific ratio.
	 */
	private void restore(Matrix m) {

		setImageMatrix(matrix);
	}

	/** Show an event in the LogCat view, for debugging */
	private void dumpEvent(MotionEvent event) {
		String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
				"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
		StringBuilder sb = new StringBuilder();
		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;
		sb.append("event ACTION_").append(names[actionCode]);
		if (actionCode == MotionEvent.ACTION_POINTER_DOWN
				|| actionCode == MotionEvent.ACTION_POINTER_UP) {
			sb.append("(pid ").append(
					action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
			sb.append(")");
		}
		sb.append("[");
		for (int i = 0; i < event.getPointerCount(); i++) {
			sb.append("#").append(i);
			sb.append("(pid ").append(event.getPointerId(i));
			sb.append(")=").append((int) event.getX(i));
			sb.append(",").append((int) event.getY(i));
			if (i + 1 < event.getPointerCount())
				sb.append(";");
		}
		sb.append("]");
		Log.d(TAG, sb.toString());
	}

}


'Programming > Android' 카테고리의 다른 글

Android onTouch 에서 ACTION_DOWN 만 들어올경우  (0) 2013.10.11
Android 실습 0823  (0) 2013.08.23
Android 채팅 소스 05  (1) 2013.08.21
Android 채팅 소스 04  (0) 2013.08.21
Android 채팅 서버 소스 01  (0) 2013.08.20

JAVA 채팅 프로그램 소스

Programming/JAVA,JSP 2013. 8. 23. 14:09 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

클라이언트


import java.awt.BorderLayout;

import java.awt.Button;

import java.awt.TextArea;

import java.awt.TextField;

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.nio.ByteOrder;


import javax.swing.JFrame;


class MyFrame extends JFrame implements ActionListener

{

public TextField tf;

public TextArea ta;

PrintWriter out;

public MyFrame(PrintWriter out)

{

this.out = out;

tf = new TextField();

ta = new TextArea();

setSize(600, 400);

setVisible(true);

add(tf, BorderLayout.SOUTH);

add(ta, BorderLayout.CENTER);

tf.addActionListener(this);

}


@Override

public void actionPerformed(ActionEvent arg0)

{

if (arg0.getSource() == tf)

{

out.println(tf.getText().toString());

tf.setText("");

}

}

}


public class client

{

public static void main(String[] args)

{

BufferedReader user = new BufferedReader(new InputStreamReader(

System.in));

Socket socket;

try

{

socket = new Socket("115.20.247.142", 1251);

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

MyFrame mf = new MyFrame(out);

ReceiveThread rt = new ReceiveThread(socket, mf.ta);

rt.start();

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


class ReceiveThread extends Thread

{

Socket socket;

TextArea ta;


public ReceiveThread(Socket socket, TextArea ta)

{

this.socket = socket;

this.ta = ta;

}


@Override

public void run()

{

BufferedReader in;

try

{

in = new BufferedReader(new InputStreamReader(

socket.getInputStream()));

while (true)

{

ta.setText(ta.getText() +"\n"+ in.readLine());

}


} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

super.run();

}

}



서버


package com.tansanc.tistory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyApplet2
{
public static void main(String[] args) throws IOException
{
int i = 1;
ServerSocket server = null;
server = new ServerSocket(1251, 5);
while (true)
{
System.out.println("Accept 대기");
Socket socket = server.accept();
System.out.println("Accept 성공");
PerClientReceiveThread pcrt = new PerClientReceiveThread(socket);
pcrt.start();
}

// Socket socket = new Socket("115.20.247.142",1251);
// InputStream is = socket.getInputStream();
// byte i = (byte)is.read();
// System.out.println(i);

}
}



package com.tansanc.tistory;

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

public class PerClientReceiveThread extends Thread
{
static ArrayList<PrintWriter> arGeneral = new ArrayList<PrintWriter>();
Socket socket;

public PerClientReceiveThread(Socket socket)
{
this.socket = socket;
}

@Override
public void run()
{
InputStream os;
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
arGeneral.add(out);

while (true)
{
String msg = in.readLine();
System.out.println(msg);
for (int i = 0; i < arGeneral.size(); i++)
{
arGeneral.get(i).println(msg);
}
}

} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
super.run();
}
}


'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 버블 정렬  (0) 2013.11.30
JAVA JTable 실습 예제  (0) 2013.08.24
JAVA 채팅 클라이언트  (0) 2013.08.23
JAVA 계산기 프로그램 부분완성  (0) 2013.08.16
JAVA 계산기 레이아웃  (0) 2013.08.16

JAVA 채팅 클라이언트

Programming/JAVA,JSP 2013. 8. 23. 13:51 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class client
{
	public static void main(String[] args)
	{
		BufferedReader user = new BufferedReader(new InputStreamReader(
				System.in));
		Socket socket;
		try
		{
			socket = new Socket("115.20.247.142", 1251);
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			ReceiveThread rt = new ReceiveThread(socket);
			rt.start();
			while (true)
			{
				out.println(user.readLine());
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class ReceiveThread extends Thread
{
	Socket socket;

	public ReceiveThread(Socket socket)
	{
		this.socket = socket;
	}

	@Override
	public void run()
	{
		BufferedReader in;
		try
		{
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			while (true)
			{
				System.out.println(in.readLine());
			}

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.run();
	}
}


'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA JTable 실습 예제  (0) 2013.08.24
JAVA 채팅 프로그램 소스  (0) 2013.08.23
JAVA 계산기 프로그램 부분완성  (0) 2013.08.16
JAVA 계산기 레이아웃  (0) 2013.08.16
JAVA 타자연습 프로그램  (0) 2013.08.13

Android 채팅 소스 05

Programming/Android 2013. 8. 21. 15:56 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc.Test130805;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	String msg;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		SharedPreferences pref = getSharedPreferences("Chatting", 0);
		String nickName = pref.getString("nickName", "noname");
		if (nickName.equals("noname")) {
			Intent intent = new Intent(this, InputNickNameActivity.class);
			startActivity(intent);
			// 최초 구동 시
		}
		setContentView(R.layout.activity_main);
		MessageReceiveThread mrt = new MessageReceiveThread();
		mrt.start();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		SharedPreferences pref = getSharedPreferences("Chatting", 0);
		String nickName = pref.getString("nickName", "noname");
		super.onResume();
	}

	public void mOnClick(View v) {
		EditText editText1 = (EditText) findViewById(R.id.editText1);
		msg = editText1.getText().toString();
		MessageSendThread mst = new MessageSendThread();
		mst.start();
	}

	public void MessageBoxPopUp(String message, String positive, String negative) {
		new AlertDialog.Builder(this).setTitle("질문").setMessage(message)
				.setPositiveButton(positive, mClick)
				.setNegativeButton(negative, mClick).show();
	}

	DialogInterface.OnClickListener mClick = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
			if (whichButton == DialogInterface.BUTTON1) {
				msg = "OK";
				MessageSendThread mst = new MessageSendThread();
				mst.start();
			} else {
				msg = "NO";
				MessageSendThread mst = new MessageSendThread();
				mst.start();
			}
		}
	};

	class MessageReceiveThread extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub

			Socket socket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				socket = new Socket("115.20.247.141", 2013);
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));

				while (true) {
					String receiveString = in.readLine();
					Message message = new Message();
					message.obj = receiveString;
					mHandler.sendMessage(message);
				}
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}

			super.run();
		}
	}

	class MessageSendThread extends Thread {
		public void run() {
			Socket socket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				socket = new Socket("115.20.247.141", 2013);
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));

				out.println(msg);

				out.close();
				in.close();
				socket.close();
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String receiveString = (String) msg.obj;
			if (receiveString.charAt(0) != 'q' ) {
				TextView textView1 = (TextView) findViewById(R.id.textView1);
				textView1.setText(textView1.getText() + "\n" + receiveString);
			}
			else
			{
				StringTokenizer st = new StringTokenizer(receiveString,":");				
				st.nextToken();
				MessageBoxPopUp(st.nextToken(),st.nextToken(),st.nextToken());
			}
		}
	};
}



'Programming > Android' 카테고리의 다른 글

Android 실습 0823  (0) 2013.08.23
PinchToZoom ImageView 로 구현  (0) 2013.08.23
Android 채팅 소스 04  (0) 2013.08.21
Android 채팅 서버 소스 01  (0) 2013.08.20
Android 채팅 소스 03  (0) 2013.08.20

Android 채팅 소스 04

Programming/Android 2013. 8. 21. 15:15 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


package com.tistory.tansanc.Test130805;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class InputNickNameActivity extends Activity implements OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_input_nick_name);
		Button saveButton = (Button)findViewById(R.id.saveButton);
		saveButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.input_nick_name, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
        SharedPreferences pref = getSharedPreferences("Chatting",0);
        SharedPreferences.Editor edit = pref.edit();
        EditText editText1  = (EditText)findViewById(R.id.editText1);
        edit.putString("nickName", editText1.getText().toString());
        edit.commit();
        Toast.makeText(this, "nickName : " + editText1.getText().toString(), Toast.LENGTH_LONG);
        finish();
	}

}



package com.tistory.tansanc.Test130805;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
public class MainActivity extends Activity {
    String msg;
 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences pref = getSharedPreferences("Chatting",0);
        String nickName = pref.getString("nickName", "noname");
        if( nickName.equals("noname") )
        {
        	Intent intent = new Intent(this, InputNickNameActivity.class);
        	startActivity(intent);
        	// 최초 구동 시
        }
        setContentView(R.layout.activity_main);
        MessageReceiveThread mrt = new MessageReceiveThread();
        mrt.start();
    }
 
    public void mOnClick(View v) {
        EditText editText1 = (EditText) findViewById(R.id.editText1);
        msg = editText1.getText().toString();
        MessageSendThread mst = new MessageSendThread();
        mst.start();
    }
 
    class MessageReceiveThread extends Thread {
        @Override
        public void run() {
            // TODO Auto-generated method stub
 
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
 
            try {
                socket = new Socket("115.20.247.141", 2013);
                out = new PrintWriter(new OutputStreamWriter(
                        socket.getOutputStream(), "utf-8"), true);
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream(), "utf-8"));
                 
                while(true)
                {
                    String receiveString = in.readLine();
                    Message message = new Message();
                    message.obj = receiveString;
                    mHandler.sendMessage(message);
                }
            } catch (UnknownHostException e) {
            } catch (IOException e) {
            }
 
            super.run();
        }
    }
 
    class MessageSendThread extends Thread {
        public void run() {
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
 
            try {
                socket = new Socket("115.20.247.141", 2013);
                out = new PrintWriter(new OutputStreamWriter(
                        socket.getOutputStream(), "utf-8"), true);
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream(), "utf-8"));
 
                out.println(msg);
 
                out.close();
                in.close();
                socket.close();
            } catch (UnknownHostException e) {
            } catch (IOException e) {
            }
        }
    }
 
    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String receiveString = (String) msg.obj;
            TextView textView1 = (TextView) findViewById(R.id.textView1);
            textView1.setText(textView1.getText() + "\n" + receiveString);
        }
    };
}


'Programming > Android' 카테고리의 다른 글

PinchToZoom ImageView 로 구현  (0) 2013.08.23
Android 채팅 소스 05  (1) 2013.08.21
Android 채팅 서버 소스 01  (0) 2013.08.20
Android 채팅 소스 03  (0) 2013.08.20
Android 채팅 소스 02  (0) 2013.08.20

Android 채팅 서버 소스 01

Programming/Android 2013. 8. 20. 18:26 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

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

class perClientThread extends Thread {
	Socket socket;
	static ArrayList alp = new ArrayList();

	public perClientThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"), true);
		
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream(), "utf-8"));
			String inputLine, outputLine;
			alp.add(out);

			while ((inputLine = in.readLine()) != null) {
				for(int i = 0 ; i < alp.size() ; i++)
				{
					alp.get(i).println(inputLine);
				}
				System.out.println(inputLine);
			}
			alp.remove(out);
			out.close();
			in.close();
			socket.close();
			super.run();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ReceiveThread extends Thread {
	ServerSocket ss;

	@Override
	public void run() {
		try {
			ss = new ServerSocket(2013);
			// 수신
			while (true) {
				Socket clientSocket = ss.accept();
				perClientThread pct = new perClientThread(clientSocket);
				pct.start();
			}
			// 수신성공
			// system.out.println
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
public class Test {
	public static void main(String[] args) {
		ReceiveThread rt = new ReceiveThread();
		rt.start();
	}
}


'Programming > Android' 카테고리의 다른 글

Android 채팅 소스 05  (1) 2013.08.21
Android 채팅 소스 04  (0) 2013.08.21
Android 채팅 소스 03  (0) 2013.08.20
Android 채팅 소스 02  (0) 2013.08.20
Android 채팅 소스 01  (0) 2013.08.20

Android 채팅 소스 03

Programming/Android 2013. 8. 20. 17:58 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc.Test130805;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	String msg;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		MessageReceiveThread mrt = new MessageReceiveThread();
		mrt.start();
	}

	public void mOnClick(View v) {
		EditText editText1 = (EditText) findViewById(R.id.editText1);
		msg = editText1.getText().toString();
		MessageSendThread mst = new MessageSendThread();
		mst.start();
	}

	class MessageReceiveThread extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub

			Socket socket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				socket = new Socket("115.20.247.141", 2013);
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));
				
				while(true)
				{
					String receiveString = in.readLine();
					Message message = new Message();
					message.obj = receiveString;
					mHandler.sendMessage(message);
				}
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}

			super.run();
		}
	}

	class MessageSendThread extends Thread {
		public void run() {
			Socket socket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				socket = new Socket("115.20.247.141", 2013);
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));

				out.println(msg);

				out.close();
				in.close();
				socket.close();
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String receiveString = (String) msg.obj;
			TextView textView1 = (TextView) findViewById(R.id.textView1);
			textView1.setText(textView1.getText() + "\n" + receiveString);
		}
	};
}


'Programming > Android' 카테고리의 다른 글

Android 채팅 소스 04  (0) 2013.08.21
Android 채팅 서버 소스 01  (0) 2013.08.20
Android 채팅 소스 02  (0) 2013.08.20
Android 채팅 소스 01  (0) 2013.08.20
Android Download html  (0) 2013.08.20