简体   繁体   中英

Writing and Reading data to and from Socket on keyPressed()

I have a Processing code that reads from and writes to a Python app via Sockets. I want it to write on keyPressed and read on keyReleased actions.

Problem is, there is no action being performed on those two events. It refuses to connect to the Socket on key actions.

Here is the java code :

import java.io.*;
import java.net.*;
String result;
String status;
String reply;

void setup(){
    size(1000, 450);
    textFont(createFont("Arial", 20));
    result = "You Said!";
    reply = "He Replied: ";
    status = "...";
}
void draw(){
    background(0);
    text(result, 0, 50);
    text(reply, 0, 150);
    text(status, 0, 250);
}
public void keyPressed() {
  status = "PRESSED";
  try {
    Socket clientSocket = new Socket("localhost", 8089);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    outToServer.writeBytes(result + '\n');
    outToServer.flush();
  }
  catch(Exception e) {
    println(e);
  }
}
public void keyReleased () {
  status = "RELEASED";
  try {
    Socket clientSocket = new Socket("localhost", 8089);
    BufferedReader inFromServer = new BufferedReader(
    new InputStreamReader(clientSocket.getInputStream()));  
    reply = inFromServer.readLine();
  }
  catch(Exception e) {
    println(e);
  }
}

The socket connection isn't happening at all. The status string isn't changing. Is there anywhere I'm going wrong? Logically this seems correct.

You should use Client and Server in Processing. See the following two mini apps:

import processing.net.*;

Server s;
Client c;
String reply = "n/a";

void setup() {
  size(300, 200);
  s = new Server(this, 8089);
}

void draw()  {
  background(50);
  // Receive data from client
  c = s.available();
  if (c != null) {
    reply = c.readString();
  }

  fill(255);
  text(reply, 100, 100);  
}

and the client code

import processing.net.*;

Client c;
String msg;

void setup() {
  size(300, 200);
  c = new Client(this, "127.0.0.1", 8089);
}

void draw() {
  background(204);
}

void keyPressed() {
  msg = "Hello world";
  c.write(msg + "\n");
}

You need to start the server first.


Verify it's not due to the key event handling methods, by trying out this super simple Processing sketch:

import java.net.*;

try {
  Socket clientSocket = new Socket("localhost", 8089);
}
catch (Exception e) {
  println(e);
}

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