- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试让 iPhone 客户端与 Java 服务器对话,这是 Java 服务器代码:
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class Server {
// a unique ID for each connection
private static int uniqueId;
// an ArrayList to keep the list of the Client
private ArrayList<ClientThread> al;
// if I am in a GUI
private ServerGUI sg;
// to display time
private SimpleDateFormat sdf;
// the port number to listen for connection
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
/*
* server constructor that receive the port to listen to for connection as parameter
* in console
*/
public Server(int port) {
this(port, null);
}
public Server(int port, ServerGUI sg) {
// GUI or not
this.sg = sg;
// the port
this.port = port;
// to display hh:mm:ss
sdf = new SimpleDateFormat("HH:mm:ss");
// ArrayList for the Client list
al = new ArrayList<ClientThread>();
}
public void start() {
keepGoing = true;
/* create socket server and wait for connection requests */
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept(); // accept connection
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket); // make a thread of it
al.add(t); // save it in the ArrayList
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("localhost", port);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
/*
* to broadcast a message to all Clients
*/
private synchronized void broadcast(String message) {
// add HH:mm:ss and \n to the message
String time = sdf.format(new Date());
String messageLf = time + " " + message + "\n";
// display message on console or GUI
if(sg == null)
System.out.print(messageLf);
else
sg.appendRoom(messageLf); // append in the room window
// we loop in reverse order in case we would have to remove a Client
// because it has disconnected
for(int i = al.size(); --i >= 0;) {
ClientThread ct = al.get(i);
// try to write to the Client if it fails remove it from the list
if(!ct.writeMsg(messageLf)) {
al.remove(i);
display("Disconnected Client " + ct.username + " removed from list.");
}
}
}
// for a client who logoff using the LOGOUT message
synchronized void remove(int id) {
// scan the array list until we found the Id
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
// found it
if(ct.id == id) {
al.remove(i);
return;
}
}
}
/*
* To run as a console application just open a console window and:
* > java Server
* > java Server portNumber
* If the port number is not specified 1500 is used
*/
public static void main(String[] args) {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1500;
switch(args.length) {
case 1:
try {
portNumber = Integer.parseInt(args[0]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Server [portNumber]");
return;
}
case 0:
break;
default:
System.out.println("Usage is: > java Server [portNumber]");
return;
}
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// the Username of the Client
String username;
// the date I connect
String date;
// Constructore
ClientThread(Socket socket) {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output Streams");
try
{
// create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
username = (String) sInput.readObject();
display(username + " just connected.");
}
catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return;
}
// have to catch ClassNotFoundException
// but I read a String, I am sure it will work
catch (ClassNotFoundException e) {
}
date = new Date().toString() + "\n";
}
// try to close everything
private void close() {
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}
/*
* Write a String to the Client output stream
*/
private boolean writeMsg(String msg) {
// if Client is still connected send the message to it
if(!socket.isConnected()) {
close();
return false;
}
// write the message to the stream
try {
sOutput.writeObject(msg);
}
// if an error occurs, do not abort just inform the user
catch(IOException e) {
display("Error sending message to " + username);
display(e.toString());
}
return true;
}
}
}
现在我正在尝试通过简单地发送一条 NSString 消息来登录 iphone 客户端,这就是我在 iphone 客户端中所做的:
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 1500, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
仅使用这行代码,我就可以连接到 Java 服务器,并且在服务器中我在终端中收到此代码:
Thread trying to create Object Input/Output Streams
所以它与服务器连接,然后我尝试以这种方式发送用户名:
NSString *username = @"user";
NSData *data = [[NSData alloc] initWithData:[username dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
但在服务器终端中我收到此消息:
Exception creating new Input/output Streams: java.io.StreamCorruptedException: invalid stream header: 69616D3A
我也尝试过以这种方式发送消息:
NSData *_data=[username dataUsingEncoding:NSUTF8StringEncoding];
int data_len = [_data length];
uint8_t *readBytes = (uint8_t *)[_data bytes];
int byteIndex=0;
unsigned int len=0;
while (TRUE) {
len = ((data_len - byteIndex >= 40960) ? 40960 : (data_len-byteIndex));
if(len==0)
break;
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
len = [outputStream write:(const uint8_t *)buf maxLength:len]; byteIndex += len;
readBytes += len;
}
但同样以这种方式我收到相同的异常,我如何向java服务器发送消息?
最佳答案
对您的代码没有具体帮助,但请考虑使用 AFNetwork。 (在github上)网络总是很困难,而这个框架非常棒。
啊..您试图在java端写入对象流..它们使用专有的字节格式。您没有以预期的方式发送数据(错误的字节=>没有java对象)
我真的会选择 JSON、xml 或更简单版本的“协议(protocol)”
关于java - iPhone 客户端与 Java 服务器对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13273320/
我能想到的最好的标题,但要澄清的是,情况是这样的: 我正在开发一种类似短 url 的服务,该服务允许用户使用他们的 Twitter 帐户“登录”并发布内容。现在这项服务可以包含在 Tweetdeck
我正在开发一个应用程序,我需要用户使用类似聊天的系统相互交互。 为此,我想创建一个对话模型。据我所知,我将使用多对多关系。 具有以下模型:Conversation、User 和 Message,我想象
我试图在一个页面上多次实现 jquery 对话框 - 基本上,我想在用户单击某个人的名字时显示有关该人的更多信息。 我正在使用 php 生成页面。 我尝试这样做,并使其部分工作,但我只能使页面上的第一
我制作了一个 CustomTypeDialog 类,我想要的是使用不在 Activity 布局中的 EditText。当我尝试单击其中一个按钮时出现空指针异常,我认为这是因为它们不在 Activity
我有这个程序,我想知道如何继续它。我想让用户在“发生了什么”之后输入更多文本,然后让程序响应。感谢您的帮助 int main() { cout > answer; switch(an
我目前正在开发一个由 javafx ui 支持的 java 游戏。 玩家。应该可以和npc对话,这没问题。但我想要一定的文字效果。就像在 polemon 游戏或 Undertale 中一样,文本会逐个
所以基本上我正在尝试重写一个 bash 脚本,该脚本使用对话框 --radiolist 来选择区域设置、键盘、时间。目前,标签是与本地对应的数字(我为它创建了一个哈希表)。但因为我有大约 100 个语
有人可以告诉我如何使用 Watson Conversation 和其他服务(例如 Twilio)调用实时电话并进行对话吗? 我可以使用 Watson Conversation、Twilio 和 Nod
我有一个包含几个 .txt 文件的目录。让我们说 hi.txt hello.txt hello_test.txt test.txt 在 VBA 中使用文件对话框,如何过滤以在下拉列表中仅显示“*tes
我有一个 session 范围的 bean,ComponenteM,它被注入(inject)到请求范围的 bean,ComponenteC 中。 @Named @RequestScoped publi
我需要收集推文“集”,即用于我的研究的推特对话; 这些集合还需要满足以下条件 其中的推文数量,以及 参与人数。 我研究过 Twitter Streaming API、twitter-stream ge
我想在用户 Lync 客户端中打开一个新对话,其中包含预先确定的消息文本,但消息的收件人由用户选择,此过程从用户单击网站。 这可能吗? 最佳答案 这里的部分问题是,如果不知道要与谁开始对话(如果有意义
在 JBoss AS7 中工作,使用 Conversation Scope 管理浏览器选项卡中的用户交互。 我注意到我的页面附加了 ?cid 参数。这很棒 - 直到用户为页面添加书签然后尝试返回它!对
本地和远程标记以及Call-ID的组合用于识别对话。据说Call-ID是一次调用的唯一值。那么为什么 Call-ID 不单独用于识别对话呢? 最佳答案 一句话:“发夹”。 “Hairpinning”是
除了这行不通之外,这里没什么好说的,我不知道为什么。 Arduino 上的串行输出什么也没有。 C# 代码的输出变为等待响应,然后什么也没有。 当我启动 C# 程序时,Arduino 上的蓝牙卡 LE
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
目前正在开发一个应用程序,它甚至可以与 Android 2.2 一起使用,我使用支持库及其 AppCompat 主题来设计我的 UI。尽管大部分 UI 工作正常,但我有一个带有自定义布局的 Alert
我正在尝试对 MySQL 表 I 进行类似对话的输出,如下所示: Content From To Date Lorem
我已经创建了消息系统,在 messages.php 上我想显示消息对话,应该显示最后一条消息,但不知道查询,因为我是 php 新手,这里是数据库信息 table:conversation_chat
在那里,这是我的代码结构: 主要 Activity : public class PureDataActivity extends Activity { private TextView st
我是一名优秀的程序员,十分优秀!