본문 바로가기
프로그래밍/안드로이드

안드로이드 자바 소켓서버 통신

by -현's- 2015. 5. 10.
반응형


●소켓

- 일상 용어에서는 전구를 끼울 수 있는 도구를 말한다. 자바언어에서는 네트워크를 제어하는 클래스를 의미한다.

자바에서는 개발자가 네트워크 전문지식이 없어도 프로그래밍적으로 제어가 가능하도록 추상화시켜 제공해준다.



●예제


서버

- ChatServer.java

package chat;


import java.io.IOException;

import java.net.InetAddress;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Vector;


public class ChatServer {

//서버소켓 - 클라이언트의 접속을 받아들이는 클래스

int port=7777;

ServerSocket server;

Vector<ServerThread> connectList;

public ChatServer() {

connectList = new Vector<ServerThread>();

try {

//서버객체 생성

server = new ServerSocket(port);

while(true){

//접속자가 접속하는지 확인

//접속자가 있을때까지 대기,지연상태에 있다.

Socket client = server.accept();

InetAddress inet = client.getInetAddress();

String ip = inet.getHostAddress();

System.out.println(ip+"-접속자 발견");

//대화용 쓰레드 생성 및 소켓

ServerThread serverThread = new ServerThread(connectList, client);

System.out.println("start");

serverThread.start();

connectList.add(serverThread);

System.out.println("현재 접속자수:"+connectList.size());

}

/*

//클라이언트의 메세지를 받아들여보자(입력)

InputStream is = client.getInputStream();

//한글이 지원되지 않으므로 2바이트씩 처리하는 스트림으로 업그레이드

InputStreamReader reader;//문자기반스트림(2바이트씩 처리)

reader = new InputStreamReader(is);

//문자단위로 데이터를 처리하면 효율상 떨어지므로

//버퍼스트림으로 업그레이드

//버퍼처리된 문자기반 스트림

BufferedReader buffer = new BufferedReader(reader);

//클라이언트가 보낸 메시지를 출력해보자(출력)

OutputStream os = client.getOutputStream();

//문자기반 출력스트림

OutputStreamWriter writer = new OutputStreamWriter(os);

//버퍼처리된 문자기반 출력 스트림

BufferedWriter bufferWriter = new BufferedWriter(writer);

//int data;

String data;

while(true){

//클라이언트에서 메시지를 받는다.

//data = is.read();

//data = reader.read();

data = buffer.readLine();

//System.out.print((char)data);

System.out.println(data);

//클라이언트에게 메시지를 보낸다.

//os.write((char)data);

//os.write(data);

bufferWriter.write(data+"\n");

//출력스트림안의 데이터를 비우는것이다.

//혹시라도 남아있을수 있는 데이터를 전부 내보냄

//os.flush();

bufferWriter.flush();

}*/

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

new ChatServer();

//server = new ServerSocket(port);

}

}

 



- ServerThread.java

package chat;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.util.Vector;


public class ServerThread extends Thread{

Socket client;

BufferedReader buffer;

BufferedWriter bufferWriter;

Vector<ServerThread> connectList;

public ServerThread(Vector<ServerThread> connectList, Socket socket) {

this.connectList = connectList;

this.client = socket;

try {

buffer = new BufferedReader(new InputStreamReader((client.getInputStream())));

bufferWriter = new BufferedWriter(new OutputStreamWriter((client.getOutputStream())));

} catch (IOException e) {

e.printStackTrace();

}

}

public void run() {

while(true){

String msg = listen();

send(msg);

}

}

//메시지 청취

public String listen(){

String msg="";

try {

msg= buffer.readLine();

System.out.println("msg:"+msg);

} catch (IOException e) {

e.printStackTrace();

}

return msg;

}

//메시지 전송

public void send(String msg){

try {

for(int i=0;i<connectList.size();i++){

ServerThread st = connectList.get(i);

st.bufferWriter.write(msg+"\n");

st.bufferWriter.flush();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

 



자바 클라이언트

- ChatClient.java

package chat;


import java.awt.BorderLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.net.UnknownHostException;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;


//윈도우창은 개발자가 명시하지 않으면 디폴트로 BorderLayout이 적용된다.

public class ChatClient extends JFrame implements ActionListener,KeyListener{

JButton btn;

JTextArea area;

JScrollPane scoll;

JTextField input;

Socket client; //대화형 소켓

String ip = "192.168.100.95";

int port = 7777;


BufferedReader bufferR;

BufferedWriter bufferW;

public ChatClient() {

btn = new JButton("접속");

area = new JTextArea();

scoll = new JScrollPane(area);

input = new  JTextField();

btn.addActionListener(this);

input.addKeyListener(this);

this.add(btn, BorderLayout.NORTH);

this.add(scoll);

this.add(input,BorderLayout.SOUTH);

setSize(300,400);

setVisible(true);

}

//채팅서버에 접속

public void connect(){

try {

client = new Socket(ip, port);

//연결된 소켓으로부터 대화를 나눌 스트림을 얻자

bufferR = new BufferedReader(new InputStreamReader(client.getInputStream()));

bufferW = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

//서버에 메시지 보내기

public void listen(){

String msg="";

try {

msg = bufferR.readLine();

area.append(msg+"\n");

} catch (IOException e) {

e.printStackTrace();

}

}

//서버에서 메시지 청취하기

public void send(){

String v = input.getText();

try {

bufferW.write(v+"\n");

bufferW.flush();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void actionPerformed(ActionEvent e) {

System.out.println("클릭");

connect();

}

public static void main(String[] args) {

new ChatClient();

}

//키를 누르골 있을때

public void keyPressed(KeyEvent e) {

}

//키를 눌렀다 땠을때

public void keyReleased(KeyEvent e) {

System.out.println("키:"+e.getKeyCode());

if(e.getKeyCode()==KeyEvent.VK_ENTER){

System.out.println("엔터");

send();

input.setText("");

listen();

}

}

//타이핑하면

public void keyTyped(KeyEvent e) {

}


}

 



안드로이드 클라이언트

- MainActivity.java

package com.example.chatclient;


import java.io.IOException;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Vector;


import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;


public class MainActivity extends Activity implements OnClickListener{

Button btn;

TextView textView;

EditText editText;

Button btn_send;

Socket client;

String ip = "192.168.100.95";

int port = 7777;

Thread thread;

ClientThread clientThread;

Handler handler;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


btn = (Button)findViewById(R.id.btn);

textView = (TextView)findViewById(R.id.textView);

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

btn_send = (Button)findViewById(R.id.btn_send);

handler = new Handler(){

public void handleMessage(Message msg) {

super.handleMessage(msg);

Bundle bundle = msg.getData();

textView.append(bundle.getString("msg")+"\n");

}

};

btn.setOnClickListener(this);

btn_send.setOnClickListener(this);

}

public void connect(){

thread = new Thread(){

public void run() {

super.run();

try {

client = new Socket(ip, port);

clientThread = new ClientThread(client, handler);

clientThread.start();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

};

thread.start();

}

@Override

public void onClick(View v) {

if(v.getId()==R.id.btn){

connect();

}

if(v.getId()==R.id.btn_send){

clientThread.send(editText.getText().toString());

editText.setText("");

}

}

}

 



- ClientThread.java

package com.example.chatclient;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.Socket;


import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.widget.TextView;


public class ClientThread extends Thread{


BufferedReader bufferR;

BufferedWriter bufferW;

Socket client;

Handler handler;


public ClientThread(Socket client, Handler handler) {

this.handler = handler;

try {

this.client = client;

//연결된 소켓으로부터 대화를 나눌 스트림을 얻음

bufferR = new BufferedReader(new InputStreamReader(client.getInputStream()));

bufferW = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

} catch (IOException e) {

e.printStackTrace();

}

}

//보내기

public void send(String data){

System.out.println("전송");

try {


System.out.println("data:"+data);

bufferW.write(data+"\n");

bufferW.flush();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//받기

public String listen(){

String msg=null;

try {

while(true){

msg=bufferR.readLine();

Message m = new Message();

Bundle bundle = new Bundle();

bundle.putString("msg", msg);

m.setData(bundle);

handler.sendMessage(m);

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return msg;

}

public void run() {

super.run();

listen();

}

}

 



- activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   

 xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/LinearLayout1"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context="${relativePackage}.${activityClass}" >


    <Button 

        android:id="@+id/btn"

        android:layout_width="wrap_content"

        android:layout_height="0dp"

        android:text="접속"

        android:layout_weight="1"

        android:layout_gravity="center_horizontal"/>

    

<TextView 

   android:id="@+id/textView"

   android:layout_width="match_parent"

   android:layout_height="0dp"

        android:layout_weight="10"/>    

    

    

    

    <EditText 

        android:id="@+id/editText"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:background="#ffdd00"

        android:layout_weight="1"/>

    

    <Button 

        android:id="@+id/btn_send"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:text="전송"

        android:layout_weight="1"

        android:layout_gravity="center_horizontal"/>

    

    


</LinearLayout>

 








반응형

댓글