简体   繁体   English

在keyPressed()上写入和从Socket读取数据

[英]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. 我有一个处理代码,通过套接字读取和写入Python应用程序。 I want it to write on keyPressed and read on keyReleased actions. 我想让它写在keyPressed上并读取keyReleased动作。

Problem is, there is no action being performed on those two events. 问题是,没有对这两个事件执行任何操作。 It refuses to connect to the Socket on key actions. 它拒绝在关键操作上连接到Socket。

Here is the java code : 这是java代码:

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. 您应该在Processing中使用ClientServer 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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