no message

This commit is contained in:
wanjian
2016-12-03 12:51:40 +08:00
commit 565dca662d
44 changed files with 1743 additions and 0 deletions

9
.gitignore vendored Normal file
View File

@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
/.idea/

22
.idea/compiler.xml generated Normal file
View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>

3
.idea/copyright/profiles_settings.xml generated Normal file
View File

@@ -0,0 +1,3 @@
<component name="CopyrightManager">
<settings default="" />
</component>

6
.idea/encodings.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>

19
.idea/gradle.xml generated Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/lib" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

62
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>

10
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/lib/lib.iml" filepath="$PROJECT_DIR$/lib/lib.iml" />
<module fileurl="file://$PROJECT_DIR$/屏幕共享A.iml" filepath="$PROJECT_DIR$/屏幕共享A.iml" />
</modules>
</component>
</project>

12
.idea/runConfigurations.xml generated Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>

1
app/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

30
app/build.gradle Normal file
View File

@@ -0,0 +1,30 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "sharescreen.wanjian.com.a"
minSdkVersion 9
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
// compile 'com.mogujie:screenshare:0.0.1-SNAPSHOT'
testCompile 'junit:junit:4.12'
}

17
app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/wanjian/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@@ -0,0 +1,26 @@
package sharescreen.wanjian.com.a;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("sharescreen.wanjian.com.a", appContext.getPackageName());
}
}

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sharescreen.wanjian.com.a">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="sharescreen.wanjian.com.server.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="sharescreen.wanjian.com.server.SecondActivity"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View File

@@ -0,0 +1,49 @@
package sharescreen.wanjian.com.server;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
/**
* Created by wanjian on 2016/11/19.
*/
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class ActivityLifecycleCallbacksAdapter implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sharescreen.wanjian.com.server;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* ByteArrayPool is a source and repository of <code>byte[]</code> objects. Its purpose is to
* supply those buffers to consumers who need to use them for a short period of time and then
* dispose of them. Simply creating and disposing such buffers in the conventional manner can
* considerable heap churn and garbage collection delays on Android, which lacks good management of
* short-lived heap objects. It may be advantageous to trade off some memory in the form of a
* permanently allocated pool of buffers in order to gain heap performance improvements; that is
* what this class does.
* <p>
* A good candidate user for this class is something like an I/O system that uses large temporary
* <code>byte[]</code> buffers to copy data around. In these use cases, often the consumer wants
* the buffer to be a certain minimum size to ensure good performance (e.g. when copying data chunks
* off of a stream), but doesn't mind if the buffer is larger than the minimum. Taking this into
* account and also to maximize the odds of being able to reuse a recycled buffer, this class is
* free to return buffers larger than the requested size. The caller needs to be able to gracefully
* deal with getting buffers any size over the minimum.
* <p>
* If there is not a suitably-sized buffer in its recycling pool when a buffer is requested, this
* class will allocate a new buffer and return it.
* <p>
* This class has no special ownership of buffers it creates; the caller is free to take a buffer
* it receives from this pool, use it permanently, and never return it to the pool; additionally,
* it is not harmful to return to this pool a buffer that was allocated elsewhere, provided there
* are no other lingering references to it.
* <p>
* This class ensures that the total size of the buffers in its recycling pool never exceeds a
* certain byte limit. When a buffer is returned that would cause the pool to exceed the limit,
* least-recently-used buffers are disposed.
*/
public class ByteArrayPool {
/** The buffer pool, arranged both by last use and by buffer size */
private List<byte[]> mBuffersByLastUse = new LinkedList<byte[]>();
private List<byte[]> mBuffersBySize = new ArrayList<byte[]>(64);
/** The total size of the buffers in the pool */
private int mCurrentSize = 0;
/**
* The maximum aggregate size of the buffers in the pool. Old buffers are discarded to stay
* under this limit.
*/
private final int mSizeLimit;
/** Compares buffers by size */
protected static final Comparator<byte[]> BUF_COMPARATOR = new Comparator<byte[]>() {
@Override
public int compare(byte[] lhs, byte[] rhs) {
return lhs.length - rhs.length;
}
};
/**
* @param sizeLimit the maximum size of the pool, in bytes
*/
public ByteArrayPool(int sizeLimit) {
mSizeLimit = sizeLimit;
}
/**
* Returns a buffer from the pool if one is available in the requested size, or allocates a new
* one if a pooled one is not available.
*
* @param len the minimum size, in bytes, of the requested buffer. The returned buffer may be
* larger.
* @return a byte[] buffer is always returned.
*/
public synchronized byte[] getBuf(int len) {
for (int i = 0; i < mBuffersBySize.size(); i++) {
byte[] buf = mBuffersBySize.get(i);
if (buf.length >= len) {
mCurrentSize -= buf.length;
mBuffersBySize.remove(i);
mBuffersByLastUse.remove(buf);
return buf;
}
}
return new byte[len];
}
/**
* Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted
* size.
*
* @param buf the buffer to return to the pool.
*/
public synchronized void returnBuf(byte[] buf) {
if (buf == null || buf.length > mSizeLimit) {
return;
}
mBuffersByLastUse.add(buf);
int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);
if (pos < 0) {
pos = -pos - 1;
}
mBuffersBySize.add(pos, buf);
mCurrentSize += buf.length;
trim();
}
/**
* Removes buffers from the pool until it is under its size limit.
*/
private synchronized void trim() {
while (mCurrentSize > mSizeLimit) {
byte[] buf = mBuffersByLastUse.remove(0);
mBuffersBySize.remove(buf);
mCurrentSize -= buf.length;
}
}
}

View File

@@ -0,0 +1,82 @@
package sharescreen.wanjian.com.server;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
/**
* Created by wanjian on 2016/11/20.
*/
public class ClientHandler extends Handler {
private BufferedOutputStream outputStream;
private final int MSG = 1;
private void writeInt(OutputStream outputStream, int v) throws IOException {
outputStream.write(v >> 24);
outputStream.write(v >> 16);
outputStream.write(v >> 8);
outputStream.write(v);
}
public void sendData(byte[] datas) {
removeMessages(MSG);
Message message = obtainMessage();
message.what = MSG;
message.obj = datas;
sendMessage(message);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (outputStream != null) {
try {
byte[] data = (byte[]) msg.obj;
Log.d("RecorderManager", "length : " + data.length);
long s = System.currentTimeMillis();
outputStream.write(RecorderManager.VERSION);
writeInt(outputStream, data.length);
outputStream.write(data);
outputStream.flush();
Log.d("RecorderManager", "write : " + (System.currentTimeMillis() - s));
} catch (IOException e) {
try {
outputStream.close();
} catch (IOException e1) {
}
outputStream = null;
}
}
}
public ClientHandler(Socket socket) {
try {
outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024 * 200);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
post(new Runnable() {
@Override
public void run() {
try {
outputStream.close();
} catch (Exception e) {
}
getLooper().quit();
}
});
}
}

View File

@@ -0,0 +1,59 @@
package sharescreen.wanjian.com.server;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Date;
import sharescreen.wanjian.com.a.R;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "ScreeenSend";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = (TextView) findViewById(R.id.tv);
findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RecorderManager.getInstance(MainActivity.this)
.startRecorder(MainActivity.this, 0.5f);
}
});
findViewById(R.id.jieshu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RecorderManager.getInstance(MainActivity.this)
.stopRecorder();
}
});
findViewById(R.id.act2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), SecondActivity.class));
}
});
new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv.setText(new Date().toLocaleString());
sendEmptyMessageDelayed(0,1000);
}
}.sendEmptyMessage(0);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sharescreen.wanjian.com.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* A variation of {@link ByteArrayOutputStream} that uses a pool of byte[] buffers instead
* of always allocating them fresh, saving on heap churn.
*/
public class PoolingByteArrayOutputStream extends ByteArrayOutputStream {
/**
* If the {@link #PoolingByteArrayOutputStream(ByteArrayPool)} constructor is called, this is
* the default size to which the underlying byte array is initialized.
*/
private static final int DEFAULT_SIZE = 256;
private final ByteArrayPool mPool;
/**
* Constructs a new PoolingByteArrayOutputStream with a default size. If more bytes are written
* to this instance, the underlying byte array will expand.
*/
public PoolingByteArrayOutputStream(ByteArrayPool pool) {
this(pool, DEFAULT_SIZE);
}
/**
* Constructs a new {@code ByteArrayOutputStream} with a default size of {@code size} bytes. If
* more than {@code size} bytes are written to this instance, the underlying byte array will
* expand.
*
* @param size initial size for the underlying byte array. The value will be pinned to a default
* minimum size.
*/
public PoolingByteArrayOutputStream(ByteArrayPool pool, int size) {
mPool = pool;
buf = mPool.getBuf(Math.max(size, DEFAULT_SIZE));
}
@Override
public void close() throws IOException {
mPool.returnBuf(buf);
buf = null;
super.close();
}
@Override
public void finalize() {
mPool.returnBuf(buf);
}
/**
* Ensures there is enough space in the buffer for the given number of additional bytes.
*/
private void expand(int i) {
/* Can the buffer handle @i more bytes, if not expand it */
if (count + i <= buf.length) {
return;
}
byte[] newbuf = mPool.getBuf((count + i) * 2);
System.arraycopy(buf, 0, newbuf, 0, count);
mPool.returnBuf(buf);
buf = newbuf;
}
@Override
public synchronized void write(byte[] buffer, int offset, int len) {
expand(len);
super.write(buffer, offset, len);
}
@Override
public synchronized void write(int oneByte) {
expand(1);
super.write(oneByte);
}
}

View File

@@ -0,0 +1,303 @@
package sharescreen.wanjian.com.server;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wanjian on 2016/11/20.
*/
public class RecorderManager {
private static final String TAG = RecorderManager.class.getName();
public static final byte VERSION = 1;
private static RecorderManager sManager;
private Context mContext;
private Handler mCompressHandler;
private List<ClientHandler> mClientHandlers = new ArrayList<>();
private Bitmap mDrawingBoard;
private Canvas mCanvas = new Canvas();
private View rootView;
private Handler mUIHandler = new Handler(Looper.getMainLooper());
private Runnable mDrawTask = new DrawTask();
private Runnable mCompressTask = new CompressTask();
private final int MAX_CLIENT_COUNT = 10;
// private final float fps = 60f;
// private final int delay = (int) (1000 / fps);
public static synchronized RecorderManager getInstance(Context context) {
if (sManager == null) {
sManager = new RecorderManager(context);
}
return sManager;
}
private RecorderManager(Context context) {
this.mContext = context.getApplicationContext();
new HandlerThread("Compress-Thread") {
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
mCompressHandler = new Handler();
}
}.start();
startListen();
}
private void startListen() {
new Thread() {
@Override
public void run() {
super.run();
ServerSocket serverSocket = null;
for (int i = 8080; i < 65535; i++) {
try {
serverSocket = new ServerSocket(i);
final int port = i;
mUIHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, "端口: " + port, Toast.LENGTH_SHORT).show();
}
});
break;
} catch (IOException e) {
}
}
for (int i = 0; i < MAX_CLIENT_COUNT; ) {
try {
final Socket socket = serverSocket.accept();
new HandlerThread("Client-Thread") {
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
mClientHandlers.add(new ClientHandler(socket));
}
}.start();
listenRemoteTouchEvent(socket);
i++;
} catch (IOException e) {
return;
}
}
}
}.start();
}
private void listenRemoteTouchEvent(final Socket socket) {
new Thread() {
private final String DOWN = "DOWN";
private final String MOVE = "MOVE";
private final String UP = "UP";
@Override
public void run() {
super.run();
try {
MotionEvent motionEvent = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String line;
try {
line = reader.readLine();
} catch (Exception e) {
return;
}
try {
if (line.startsWith(DOWN)) {
hanlerDown(line.substring(DOWN.length()));
} else if (line.startsWith(MOVE)) {
float[] xy = getXY(line.substring(MOVE.length()));
if (motionEvent == null) {
motionEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, xy[0], xy[1], 0);
} else {
motionEvent.setAction(MotionEvent.ACTION_MOVE);
// motionEvent.setLocation(xy[0], xy[1]);
}
sendTouchEvent(motionEvent, motionEvent.getAction(), xy[0], xy[1]);
} else if (line.startsWith(UP)) {
float[] xy = getXY(line.substring(UP.length()));
sendTouchEvent(motionEvent, MotionEvent.ACTION_UP, xy[0], xy[1]);
motionEvent = null;
}
} catch (Exception e) {
}
}
} catch (Exception e) {
}
}
private void sendTouchEvent(final MotionEvent motionEvent, final int action, final float x, final float y) {
mUIHandler.post(new Runnable() {
@Override
public void run() {
try {
motionEvent.setAction(action);
motionEvent.setLocation(x, y);
rootView.dispatchTouchEvent(motionEvent);
Log.d(TAG, "touch event " + motionEvent.getAction() + " " + motionEvent.getX() + " " + motionEvent.getY());
} catch (Exception e) {
}
}
});
}
private float[] getXY(String nums) {
try {
String[] s = nums.split("#");
float scaleX = Float.parseFloat(s[0]);
float scaleY = Float.parseFloat(s[1]);
return new float[]{rootView.getWidth() * scaleX, rootView.getHeight() * scaleY};
} catch (Exception e) {
}
return new float[2];
}
private void hanlerDown(String line) {
try {
float xy[] = getXY(line);
MotionEvent motionEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, xy[0], xy[1], 0);
sendTouchEvent(motionEvent, MotionEvent.ACTION_DOWN, xy[0], xy[1]);
sendTouchEvent(motionEvent, MotionEvent.ACTION_UP, xy[0], xy[1]);
} catch (Exception e) {
}
}
}.start();
}
public void stopRecorder() {
rootView = null;
mUIHandler.removeCallbacks(mDrawTask);
if (mCompressHandler != null) {
mCompressHandler.getLooper().quit();
}
for (ClientHandler clientHandler : mClientHandlers) {
clientHandler.close();
}
// try {
// socket.close();
// } catch (Exception e) {
//
// }
sManager = null;
}
/**
* API14(ICE_CREAM_SANDWICH)及以上版本全局初始化一次即可,context任意,可以是activity也可以是其他。
* 以下版本需在每个activity的onResume中初始化,context需要传当前activity。
*
* @param context API14(ICE_CREAM_SANDWICH)以下传当前activty,其他版本建议传当前activty也可以是任意context
* @param scale 实际传输图像尺寸与手机屏幕比例
*/
public void startRecorder(final Context context, float scale) {
Point point = getScreenSize(context);
int exceptW = (int) (point.x * scale);
int exceptH = (int) (point.y * scale);
if (mDrawingBoard == null) {
mDrawingBoard = Bitmap.createBitmap(exceptW, exceptH, Bitmap.Config.RGB_565);
}
if (mDrawingBoard.getWidth() != exceptW || mDrawingBoard.getHeight() != exceptH) {
mDrawingBoard.recycle();
mDrawingBoard = Bitmap.createBitmap(exceptW, exceptH, Bitmap.Config.RGB_565);
}
mCanvas.setBitmap(mDrawingBoard);
mCanvas.scale(scale, scale);
if (context instanceof Activity) {
startRecorderActivity(((Activity) context));
} else {
Toast.makeText(context, "请下拉一下通知栏试试", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
((Application) context.getApplicationContext()).registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksAdapter() {
@Override
public void onActivityResumed(Activity activity) {
startRecorderActivity(activity);
}
});
}
}
private static Point getScreenSize(Context context) {
int w = context.getResources().getDisplayMetrics().widthPixels;
int h = context.getResources().getDisplayMetrics().heightPixels;
return new Point(w, h);
}
private void startRecorderActivity(Activity activity) {
rootView = activity.getWindow().getDecorView();
mUIHandler.removeCallbacks(mDrawTask);
mUIHandler.post(mDrawTask);
}
private class DrawTask implements Runnable {
@Override
public void run() {
if (rootView == null) {
return;
}
mUIHandler.removeCallbacks(mDrawTask);
rootView.draw(mCanvas);
mCompressHandler.removeCallbacks(mCompressTask);
mCompressHandler.post(mCompressTask);
}
}
private class CompressTask implements Runnable {
ByteArrayPool mByteArrayPool = new ByteArrayPool(1024 * 30);
PoolingByteArrayOutputStream mByteArrayOutputStream = new PoolingByteArrayOutputStream(mByteArrayPool);
@Override
public void run() {
try {//动态改变缩放比例时,由于不在该线程,可能导致bitmap被回收
mByteArrayOutputStream.reset();
long s = System.currentTimeMillis();
mDrawingBoard.compress(Bitmap.CompressFormat.JPEG, 60, mByteArrayOutputStream);
byte[] jpgBytes = mByteArrayOutputStream.toByteArray();
Log.d(TAG, "compress " + (System.currentTimeMillis() - s));
for (ClientHandler clientHandler : mClientHandlers) {
clientHandler.sendData(jpgBytes);
}
mUIHandler.post(mDrawTask);
} catch (Exception e) {
}
// mUIHandler.postDelayed(mDrawTask, delay);
}
}
}

View File

@@ -0,0 +1,19 @@
package sharescreen.wanjian.com.server;
import android.app.Activity;
import android.os.Bundle;
import sharescreen.wanjian.com.a.R;
/**
* Created by wanjian on 2016/11/19.
*/
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="sharescreen.wanjian.com.a.sharescreen.wanjian.com.server.MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#e1e1e1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#e1e"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#dea"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#a38"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#390"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#e1e1e1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#e1e"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#dea"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#a38"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#390"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#e1e1e1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#e1e"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#dea"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#a38"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:background="#390"/>
</LinearLayout>
</ScrollView>
</LinearLayout>

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="sharescreen.wanjian.com.a.sharescreen.wanjian.com.server.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="0"
android:id="@+id/tv"
android:textColor="#ff0000"/>
<Button
android:id="@+id/ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="开启"/>
<Button
android:id="@+id/jieshu"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="结束"/>
<Button
android:id="@+id/act2"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启新Act"/>
</LinearLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View File

@@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>

View File

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">屏幕共享A</string>
</resources>

View File

@@ -0,0 +1,11 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

View File

@@ -0,0 +1,17 @@
package sharescreen.wanjian.com.a;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

23
build.gradle Normal file
View File

@@ -0,0 +1,23 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

17
gradle.properties Normal file
View File

@@ -0,0 +1,17 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

160
gradlew vendored Executable file
View File

@@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
lib/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

8
lib/build.gradle Normal file
View File

@@ -0,0 +1,8 @@
apply plugin: 'java'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"

View File

@@ -0,0 +1,205 @@
package com.client;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Client extends JFrame {
JLabel label;
public Client() throws IOException {
setLayout(new BorderLayout(0, 0));
JPanel ipPanel = new JPanel(new BorderLayout(5, 5));
final JTextField ipField = new JTextField();
ipPanel.add(ipField, BorderLayout.CENTER);
ipPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel portPanel = new JPanel(new BorderLayout(5, 5));
final JTextField portField = new JTextField();
portPanel.add(portField, BorderLayout.CENTER);
portPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel btnPanel = new JPanel(new BorderLayout(5, 5));
JButton btn = new JButton("链接");
btnPanel.add(btn, BorderLayout.CENTER);
JPanel panelContainer = new JPanel(new BorderLayout());
panelContainer.add(ipPanel, BorderLayout.NORTH);
panelContainer.add(portPanel, BorderLayout.CENTER);
panelContainer.add(btnPanel, BorderLayout.SOUTH);
JPanel panelContainer2 = new JPanel(new BorderLayout());
panelContainer2.add(panelContainer, BorderLayout.NORTH);
label = new JLabel();
// Image image = ImageIO.read(new File("/Users/wanjian/Desktop/img.jpg"));
// label.setIcon(new ImageIcon(image));
label.setBorder(new EmptyBorder(5, 5, 5, 5));
add(panelContainer2, BorderLayout.NORTH);
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(360, 20, 350, 600);
setTitle("屏幕共享 by 万剑");
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
read(ipField.getText(), portField.getText());
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
super.mouseClicked(mouseEvent);
System.out.println(mouseEvent);
int x = mouseEvent.getX();
int y = mouseEvent.getY();
try {
writer.write("DOWN"+(x*1.0f/label.getWidth() )+ "#" + (y*1.0f/label.getHeight()));
writer.newLine();
writer.flush();
} catch (Exception e) {
}
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
super.mouseReleased(mouseEvent);
System.out.println("mouseReleased " );
try {
int x = mouseEvent.getX();
int y = mouseEvent.getY();
writer.write("UP"+(x*1.0f/label.getWidth() )+ "#" + (y*1.0f/label.getHeight()));
writer.newLine();
writer.flush();
} catch (Exception e) {
}
}
});
label.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent mouseEvent) {
super.mouseDragged(mouseEvent);
System.out.println("mouseDragged "+mouseEvent.getX()+" "+mouseEvent.getY());
try {
int x = mouseEvent.getX();
int y = mouseEvent.getY();
writer.write("MOVE"+(x*1.0f/label.getWidth() )+ "#" + (y*1.0f/label.getHeight()));
writer.newLine();
writer.flush();
} catch (Exception e) {
}
}
});
// label.addMouseWheelListener(new MyMouseAdapter(){
// @Override
// public void mouseWheelMoved(MouseWheelEvent mouseWheelEvent) {
// super.mouseWheelMoved(mouseWheelEvent);
// System.out.println("mouseWheelMoved "+mouseWheelEvent);
// }
//
// // @Override
//// public void mouseDragged(MouseEvent mouseEvent) {
//// super.mouseDragged(mouseEvent);
//// System.out.println("mouseDragged");
//// }
// });
}
BufferedWriter writer;
private void read(final String ip, final String port) throws IOException {
new Thread() {
@Override
public void run() {
super.run();
try {
Socket socket = new Socket(ip, Integer.parseInt(port));
BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
byte[] bytes = null;
while (true) {
long s1 = System.currentTimeMillis();
int version = inputStream.read();
if (version == -1) {
return;
}
int length = readInt(inputStream);
if (bytes == null) {
bytes = new byte[length];
}
if (bytes.length < length) {
bytes = new byte[length];
}
int read = 0;
while ((read < length)) {
read += inputStream.read(bytes, read, length - read);
}
InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
long s2 = System.currentTimeMillis();
Image image = ImageIO.read(byteArrayInputStream);
label.setIcon(new ScaleIcon(new ImageIcon(image)));
long s3 = System.currentTimeMillis();
// System.out.println("读取: " + (s2 - s1) + " 解码: " + (s3 - s2) + " " + length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private int readInt(InputStream inputStream) throws IOException {
int b1 = inputStream.read();
int b2 = inputStream.read();
int b3 = inputStream.read();
int b4 = inputStream.read();
return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
}
public static void main(String[] args) throws IOException {
new Client().setVisible(true);
}
}

View File

@@ -0,0 +1,46 @@
package com.client;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
/**
* Created by wanjian on 2016/11/20.
*/
public class ScaleIcon implements Icon {
private BufferedImage i = null;
private Icon icon = null;
public ScaleIcon(Icon icon) {
this.icon = icon;
}
@Override
public int getIconHeight() {
return icon.getIconHeight();
}
@Override
public int getIconWidth() {
return icon.getIconWidth();
}
public void paintIcon(Component c, Graphics g, int x, int y) {
float wid = c.getWidth();
float hei = c.getHeight();
int iconWid = icon.getIconWidth();
int iconHei = icon.getIconHeight();
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.scale(wid / iconWid, hei / iconHei);
icon.paintIcon(c, g2d, 0, 0);
}
}

1
settings.gradle Normal file
View File

@@ -0,0 +1 @@
include ':app', ':lib'