简体   繁体   中英

How to send data through socket in java

I am making a simple android app to send string to server(created in python). I am connecting to server using socket in separate thread as Shown in code. I want to send string on button click. This is java code:

public class MainActivity extends AppCompatActivity {

private Socket socket;
Button btn;

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

    new Thread(new ClientThread()).start();

    btn = (Button) findViewById(R.id.button);
    if (socket != null){
        try {
            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, true);
            writer.println("1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ClientThread implements Runnable{
    @Override
    public void run() {
        try {
            socket = new Socket("192.168.0.12", 80);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And this my python server

import socket

host = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, 80))

print("ip = ", host)

s.listen(1)
print("Listening")

while True:
    conn, addr = s.accept()
    print(addr, " connected to us")
    conn.sendall(bytes("Hello", "utf-8"))
    while True:
        try:
            data = bytes.decode(conn.recv(1024), "utf-8")
            print(data)
        except:
            break
    
    

and this is server output

ip =  192.168.0.12
Listening
('192.168.0.6', 45903)  connected to us

Please give me suggestion to send data to server

    Socket s = new Socket("address",port);
    OutputStream os = s.getOutputStream();
    //do write
    os.close();
    s.shutdownOutput();

When you want to use the socket next time,ReCreate it and connect.

s.shutdownOutput() 

This method do write data to server when you invoked it;

After so much research I found solution for my problem. Here I am sharing my code

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.button);
    btn2 = (Button) findViewById(R.id.button2);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new UPThread()).start();
        }
    });

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new DOWNThread()).start();
        }
    });

}
private PrintWriter output;
private BufferedReader input;
class UPThread implements Runnable{
    @Override
    public void run() {
        try {
            socket = new Socket("192.168.43.235", 80);
            output = new PrintWriter(socket.getOutputStream());
            output.write("UP");
            output.flush();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class DOWNThread implements Runnable{
    @Override
    public void run() {
        try{
            socket = new Socket("192.168.43.235", 80);
            output = new PrintWriter(socket.getOutputStream());
            output.write("DOWN");
            output.flush();
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

I run the thread on button click so it will be easy for me to send simple instruction to my IOT project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM