背景故事: 我创建了一个可以与我的工作服务器连接的条形码扫描应用程序。条形码应用程序功能完美,但是,我没有与服务器的套接字连接的经验。因此,为了不搞乱条形码应用程序中的任何代码,我复制了一个套接字连接的教程并对其进行了编辑。一旦我可以获得测试代码来完成连接并来回发送数据,我将把它实现到Barcode应用程序中。
问题: 当我点击“连接到服务器”按钮时,我得到了这个:
03-23 11:55:52.174 6438-6459/com.example.vipin.client I/Client: Waiting for message from server...
下面粘贴的是代码。出于安全原因,我已删除了IP地址和端口。
package com.example.vipin.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Client extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = Client.class.getSimpleName();
public static final int SERVERPORT = 0000;
public static final String SERVER_IP = "000.000.0.0";
ClientThread clientThread;
Thread thread;
TextView messageTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageTv = (TextView) findViewById(R.id.messageTv);
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
messageTv.append(message + "\n");
}
});
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
messageTv.setText("");
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.send_data) {
clientThread.sendMessage("Hello from Client");
Log.i(TAG, "Sending message to server...");
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
Log.i(TAG, "Waiting for message from server...");
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
Log.i(TAG, "Message received from the server : " + message);
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
updateMessage(getTime() + " | Server : " + message);
break;
}
updateMessage(getTime() + " | Server : " + message);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
void sendMessage(String message) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
按钮点击事件的日志位于https://pastebin.com/6wbvLj6w
答案 0 :(得分:0)
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import javax.imageio.ImageIO;
public class ServerPrintScreen
extends Thread {
private ServerSocket serverSocket;
public ServerPrintScreen(int port)
throws IOException, SQLException, ClassNotFoundException, Exception {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(0);
}
public void run() {
try {
while (true) {
Socket clientSocket = serverSocket.accept();
Throwable localThrowable3 = null;
try {
System.out.println("client connected");
clientSocket.setKeepAlive(true);
String httpResponse = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nAccept-Ranges: bytes\r\nContent-Disposition: inline;filename=screenShot.jpg\r\nContent-Type: image/jpg\r\n\r\n";
BufferedImage originalImage = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
ImageIO.write(originalImage, "jpg", clientSocket.getOutputStream());
clientSocket.getOutputStream().flush();
clientSocket.getOutputStream().close();
clientSocket.close();
System.out.println("sent");
} catch (Throwable localThrowable1) {
localThrowable3 = localThrowable1;
throw localThrowable1;
} finally {
if (clientSocket != null) {
if (localThrowable3 != null) {
try {
clientSocket.close();
} catch (Throwable localThrowable2) {
localThrowable3.addSuppressed(localThrowable2);
}
} else {
clientSocket.close();
}
}
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, Exception {
Thread t = new ServerPrintScreen(25000);
t.start();
}
}