import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String split[];
private ListView listView1;
private ListView listView2;
private ImageView imageView;
private TextView textView;
private Socket client;
private PrintWriter printwriter;
private BufferedReader bufferedReader;
private int count = 0;
private byte[] buffer = null;
private FileOutputStream file;
private ObjectInputStream objectInputStream;
private int idCars = -1;
private int idModels = -1;
FrameLayout frameLayout;
ChatArrayAdapter chatArrayAdapter1;
ChatArrayAdapter chatArrayAdapter2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_message);
listView1 = (ListView) findViewById(R.id.listView1);
listView2 = (ListView) findViewById(R.id.listView2);
frameLayout = (FrameLayout) findViewById(R.id.frame3);
imageView = (ImageView) findViewById(R.id.imageView);
textView = (TextView) findViewById(R.id.textView);
chatArrayAdapter1 = new ChatArrayAdapter(getApplicationContext(), R.layout.activity_chat_singlemessage);
listView1.setAdapter(chatArrayAdapter1);
chatArrayAdapter1.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
listView1.setSelection(chatArrayAdapter1.getCount() - 1);
}
});
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Position = " + position, Toast.LENGTH_SHORT).show();
idCars = position;
final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
messageSender.execute();
}
listView1.setVisibility(View.GONE);
listView2.setVisibility(View.VISIBLE);
}
});
chatArrayAdapter2 = new ChatArrayAdapter(getApplicationContext(), R.layout.activity_chat_singlemessage);
listView2.setAdapter(chatArrayAdapter2);
chatArrayAdapter2.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
listView2.setSelection(chatArrayAdapter2.getCount() - 1);
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Position = " + position, Toast.LENGTH_SHORT).show();
idModels = position;
final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
messageSender.execute();
}
listView2.setVisibility(View.GONE);
frameLayout.setVisibility(View.VISIBLE);
}
});
ChatOperator chatOperator = new ChatOperator();
chatOperator.execute();
}
int kkk = 0;
int y = 0;
private class ChatOperator extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
try {
client = new Socket("192.168.1.108", 5000);
printwriter = new PrintWriter(client.getOutputStream(), true);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
objectInputStream = new ObjectInputStream(client.getInputStream());
buffer = (byte[]) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(kkk == 0) {
final Sender sender = new Sender();
sender.execute();
kkk = 1;
}
Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
receiver.execute();
}
}
private class Receiver extends AsyncTask<Void, Void, Void> {
private String message;
@Override
protected Void doInBackground(Void... params) {
while (true) {
try {
if (bufferedReader.ready()) {
message = bufferedReader.readLine();
publishProgress(null);
y = 0;
}
if(buffer != null){
file = new FileOutputStream("/sdcard/DCIM/" + count + ".jpg");
file.write(buffer);
file.close();
buffer = null;
y = 1;
publishProgress(null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void onProgressUpdate(Void... values) {
if(y == 1) {
File imgFile = new File("/sdcard/DCIM/" + count + ".jpg");
if (imgFile.exists()) {
Bitmap myImg = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myImg);
}
count++;
y = 0;
}else {
String cars = message.substring(0, 4);
message = message.substring(4);
if (cars.equals("cars")) {
split = message.split("-");
for (String aSplit : split) {
chatArrayAdapter1.add(new ChatMessage(true, aSplit));
}
}
if (cars.equals("mdls")) {
split = message.split("-");
for (String aSplit : split) {
chatArrayAdapter2.add(new ChatMessage(true, aSplit));
}
}
if (cars.equals("dtls")) {
textView.setText(message);
}
}
}
}
private class Sender extends AsyncTask<Void, Void, Void> {
private String message = "";
@Override
protected void onPreExecute() {
if(idCars != -1){
message = "mdls" + split[idCars];
idCars = -1;
}
if(idModels != -1){
message = "dtls" + split[idModels];
idModels = -1;
}
}
@Override
protected Void doInBackground(Void... params) {
//message = editText.getText().toString();
printwriter.write(message + "\n");
printwriter.flush();
return null;
}
}
@Override
public void onBackPressed() {
System.exit(0);
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
public class Main extends Thread {
ArrayList clientOutputStreams;
int k = 0;
Socket socket;
PrintWriter writer;
static DBWorker worker;
ThreadGroup tGroup = new ThreadGroup("Clients");
String car_name = "";
String way = "C:\\Users\\NurSultan\\Desktop\\cars\\audi\\audi_a1.jpg";
public class ClientHandler implements Runnable{
BufferedReader reader;
public ClientHandler(Socket clientSocket){
try{
socket = clientSocket;
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(isReader);
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception ex){
ex.printStackTrace();
}
}
@Override
public void run() {
String message;
try{
while ((message = reader.readLine()) != null){
Car car = new Car();
try {
if(message.equals("")) {
String query = "select * from cars";
Statement statement = worker.getConnection().createStatement();
ResultSet resultSet = statement.executeQuery(query);
String cars = "cars";
while (resultSet.next()) {
car.setCars_name(resultSet.getString("cars_name"));
cars += String.valueOf(car) + "-";
}
System.out.println(cars);
tellEveryone(String.valueOf(cars));
}else{
String four = message.substring(0, 4);
message = message.substring(4);
if(four.equals("mdls")){
//convert "A" to "a"
char[] ccc = message.toCharArray();
message = "";
for(int i=0; i<ccc.length; i++){
if(!((int)ccc[i]>=97 && (int)ccc[i]<=122) && !(ccc[i] >= 0 && ccc[i] <= 9)){
ccc[i] = (char)((int)ccc[i] + 32);
}
message += ccc[i];
}
car_name = message;
System.out.println("char message = " + message);
String query = "select * from " + message + "_models";
String mdls = "mdls";
Statement statement = worker.getConnection().createStatement();
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()){
car.setCars_name(resultSet.getString("models_name"));
mdls += String.valueOf(car) + "-";
}
System.out.println(mdls);
tellEveryone(mdls);
}else{
if(four.equals("dtls")){
way = "C:\\Users\\NurSultan\\Desktop\\cars\\audi\\audi_a1.jpg";
//sendPhoto(way);
//telEveryone("dtls" + "об машине");
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
public static void main(String[] args){
System.out.println("Server started...");
System.out.println("Listening port 5000");
System.out.println();
worker = new DBWorker();
new Main().go();
}
public void go(){
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSocket = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
new Thread(tGroup, new ClientHandler(clientSocket), String.valueOf(k)).start();
System.out.println("got a connection");
sendPhoto(way);
k++;
}
}catch (Exception e){
e.printStackTrace();
}
}
public void tellEveryone(String message){
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()){
try{
writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
public void sendPhoto(String way){
ObjectOutputStream objectOutputStream;
try {
FileInputStream file = new FileInputStream(way);
byte[] buffer = new byte[file.available()];
file.read(buffer);
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(buffer);
objectOutputStream.flush();
System.out.println("Send foto");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}