I am trying to test player position communication between a client and a server. I am doing this by building a game environment where the other player's position is also displayed. They connect properly, but both the windows are blank white. If I terminate one program only then the other displays the playground. Also in the action listener which listens for the timer only sends the data and doesn't proceed. Can I get help for displaying the windows properly and fixing the action listener?
Here is the client code :
public class SamplePlayerClient1
{
private static JFrame window = new JFrame("Sample Player Client 1");
private static class Ground extends JPanel {
private static final long serialVersionUID = 1L;
private int px = 50, py = 235, ex, ey, key;
private DataWriter writer;
private DataReader reader;
private ActionListener timerListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
writer.send(px, py);
System.out.println("data sent");
ex = reader.read().x;
ey = reader.read().y;
System.out.println("Data read");
} catch (IOException e1) {
e1.printStackTrace();
}
repaint();
}
};
private Timer animator = new Timer(30, timerListener);
private KeyAdapter keyListener = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
key = e.getKeyCode();
if(key == KeyEvent.VK_UP) {
py -= 8;
if(py < 0) {
py = 0;
}
} else if(key == KeyEvent.VK_DOWN) {
py += 8;
if(py > 430) {
py = 430;
}
} else if(key == KeyEvent.VK_LEFT) {
px -= 8;
if(px < 0) {
px = 0;
}
} else if(key == KeyEvent.VK_RIGHT) {
px += 8;
if(px > 455) {
px = 455;
}
}
}
};
Ground() throws UnknownHostException, IOException {
Socket soc = new Socket(InetAddress.getByName("192.168.0.3"), 9998);
System.out.println("client 2 connected");
writer = new DataWriter(soc);
reader = new DataReader(soc);
animator.start();
addKeyListener(keyListener);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
requestFocus();
g.setColor(Color.BLACK);
g.fillRect(px, py, 30, 30);
g.setColor(Color.RED);
g.fillRect(ex, ey, 30, 30);
}
}
private static class DataWriter {
private OutputStreamWriter writer;
private String point = "";
DataWriter(Socket soc) throws IOException {
writer = new OutputStreamWriter(soc.getOutputStream());
}
void send(int x, int y) throws IOException {
point = "" + x;
point += ",";
point += y;
point += "\n";
writer.write(point);
writer.flush();
}
}
private static class DataReader {
private InputStreamReader is;
private BufferedReader reader;
private String point = "";
DataReader(Socket soc) throws IOException {
is = new InputStreamReader(soc.getInputStream());
reader = new BufferedReader(is);
}
Point read() throws IOException {
point = reader.readLine();
int x = Integer.parseInt(point.split(",")[0]);
int y = Integer.parseInt(point.split(",")[1]);
return new Point(x, y);
}
}
public static void main(String [] args) throws UnknownHostException, IOException {
Ground ground = new Ground();
window.setContentPane(ground);
window.setSize(600, 600);
window.setLocation(0, 0);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
I don't see the problem but I did see that:
ex = reader.read().x;
ey = reader.read().y;
This reads two lines and throws away the y from the first and the x from the second.
Should be:
Point p = reader.read();
ex = p.x;
ey = p.y;
The peer might not generate a point for you to read every time you write one so the reading of the points from the peer should not occur in the event handler that writes a point to the peer.
Related
I need help making my color cycle continue without stopping
I tried to loop the timer but that didn't work also im using bunifu
private void Form2_Load(object sender, EventArgs e)
{
panelColor(panel1, logo);
bunifuColorTransition1.ProgessValue = 0;
bunifuColorTransition1.Color1 = panel1.BackColor;
bunifuColorTransition1.Color2 = Color.FromArgb(210, 132, 120);
timer1.Start();
}
public void panelColor(Panel h, BunifuImageButton x)
{
panel1 = h;
logo = x;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (bunifuColorTransition1.ProgessValue < 100)
{
BunifuColorTransition bunifuColorTransition = bunifuColorTransition1;
int progessValue = bunifuColorTransition.ProgessValue;
bunifuColorTransition.ProgessValue = progessValue + 1;
panel1.BackColor = bunifuColorTransition1.Value;
logo.BackColor = bunifuColorTransition1.Value;
return;
}
timer1.Stop();
}
private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
private static final long DELAY = 1000;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private long startTime = 0L;
int num = 1;
List<VideoModel> videoList;
private Handler customHandler = new Handler();
private static final String TAG = "RecordVideoActivity";
private String videoName;
static {
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
static {
INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
}
private AutoFitTextureView mTextureView;
private ImageButton mRecordButton;
private ImageView mDots;
private ImageButton mCheckPoint;
private CameraDevice mCameraDevice;
private CameraCaptureSession mPreviewSession;
private TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
openCamera(width, height);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
configureTransform(width, height);
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
private Size mPreviewSize;
private Size mVideoSize;
private MediaRecorder mMediaRecorder;
private boolean mIsRecordingVideo;
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice cameraDevice) {
mCameraDevice = cameraDevice;
startPreview();
mCameraOpenCloseLock.release();
if (null != mTextureView) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
}
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
finish();
}
};
private Integer mSensorOrientation;
private String mNextVideoAbsolutePath;
private CaptureRequest.Builder mPreviewBuilder;
private CameraManager manager;
private String cameraId;
private boolean isFlashSupported;
private ImageButton flashButton;
private ImageButton switchCamera;
private ImageButton revertVideo;
public static final String CAMERA_BACK = "0";
private TextView mChronometer;
private String flashOpt;
private long lastSavedTime;
private String prepend;
private static Size chooseVideoSize(Size[] choices) {
for (Size size : choices) {
if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) {
return size;
}
}
Log.e(TAG, "Couldn't find any suitable video size");
return choices[choices.length - 1];
}
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getHeight() == option.getWidth() * h / w &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera2_video_image);
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (dir.isDirectory()) {
deleteDirectory(dir);
}
videoList = new ArrayList<>();
mTextureView = findViewById(R.id.textureView);
mRecordButton = findViewById(R.id.videoOnlineImageButton);
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint = findViewById(R.id.checkPoint);
mCheckPoint.setVisibility(View.GONE);
mDots = findViewById(R.id.dot);
mRecordButton.setOnClickListener(this);
flashButton = findViewById(R.id.flashVideo);
switchCamera = findViewById(R.id.switchVideo);
revertVideo = findViewById(R.id.revertVideo);
revertVideo.setVisibility(View.GONE);
mChronometer = findViewById(R.id.chronometer);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
flashOpt = prefs.getString(getString(R.string.flash_option), getString(R.string.auto));
if (flashOpt.equals(getString(R.string.flash_off)))
flashButton.setImageResource(R.drawable.flash_auto);
else if (flashOpt.equals(getString(R.string.flash_on)))
flashButton.setImageResource(R.drawable.flash_on);
else
flashButton.setImageResource(R.drawable.flash_off);
findViewById(R.id.checkPoint).setOnClickListener(this);
findViewById(R.id.flashVideo).setOnClickListener(this);
findViewById(R.id.switchVideo).setOnClickListener(this);
findViewById(R.id.revertVideo).setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
startBackgroundThread();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
if(mIsRecordingVideo)
mRecordButton.setImageResource(R.drawable.ic_video_stop);
else
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint.setEnabled(true);
startTime=SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
#Override
public void onPause() {
closeCamera();
mCheckPoint.setEnabled(false);
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
stopBackgroundThread();
super.onPause();
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int hour = mins / 60;
mChronometer.setText("" + hour + ":"
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.videoOnlineImageButton: {
if (mIsRecordingVideo) {
mDots.setVisibility(View.GONE);
mChronometer.setVisibility(View.GONE);
switchCamera.setVisibility(View.VISIBLE);
mCheckPoint.setVisibility(View.GONE);
stopRecordingVideo();
Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mNextVideoAbsolutePath)));
sendBroadcast(mediaStoreUpdateIntent);
} else {
mCheckPoint.setVisibility(View.VISIBLE);
switchCamera.setVisibility(View.GONE);
mChronometer.setVisibility(View.VISIBLE);
mDots.setVisibility(View.VISIBLE);
startRecordingVideo();
}
break;
}
case R.id.switchVideo: {
facingCamera = !facingCamera;
closeCamera();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
break;
}
case R.id.flashVideo: {
if (onFlashCheck()) {
CameraCharacteristics cameraCharacteristics = null;
try {
cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Boolean available = cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
isFlashSupported = available == null ? false : available;
switchFlash();
}
break;
}
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#SuppressLint("MissingPermission")
private void openCamera(int width, int height) {
final Activity activity = this;
if (null == activity || activity.isFinishing()) {
return;
}
manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
Log.d(TAG, "tryAcquire");
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
cameraId = manager.getCameraIdList()[1];
if (facingCamera) {
cameraId = manager.getCameraIdList()[1];
flashButton.setVisibility(View.GONE);
} else {
cameraId = manager.getCameraIdList()[0];
flashButton.setVisibility(View.VISIBLE);
}
// Choose the sizes for camera preview and video recording
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics
.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
if (map == null) {
throw new RuntimeException("Cannot get available preview/video sizes");
}
mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
width, height, mVideoSize);
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
configureTransform(width, height);
mMediaRecorder = new MediaRecorder();
manager.openCamera(cameraId, mStateCallback, null);
} catch (CameraAccessException e) {
Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
activity.finish();
} catch (NullPointerException e) {
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.");
}
}
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
closePreviewSession();
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mMediaRecorder) {
mMediaRecorder.release();
mMediaRecorder = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.");
} finally {
mCameraOpenCloseLock.release();
}
}
private void startPreview() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
Surface previewSurface = new Surface(texture);
mPreviewBuilder.addTarget(previewSurface);
mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
mPreviewSession = session;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession session) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (null == mCameraDevice) {
return;
}
try {
setUpCaptureRequestBuilder(mPreviewBuilder);
HandlerThread thread = new HandlerThread("CameraPreview");
thread.start();
mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
if (onFlashCheck()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.VISIBLE);
}
});
if (flashOpt.equals(getString(R.string.auto)))
builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
else if (flashOpt.equals(getString(R.string.flash_off)))
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
else
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
} else
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.GONE);
}
});
}
private void configureTransform(int viewWidth, int viewHeight) {
if (null == mTextureView || null == mPreviewSize) {
return;
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / mPreviewSize.getHeight(),
(float) viewWidth / mPreviewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
}
mTextureView.setTransform(matrix);
}
private void setUpMediaRecorder() throws IOException {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
File file = getVideoFilePath(this);
mNextVideoAbsolutePath = file.getAbsolutePath();
videoName = file.getName();
mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
mMediaRecorder.setVideoEncodingBitRate(10000000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
switch (mSensorOrientation) {
case SENSOR_ORIENTATION_DEFAULT_DEGREES:
mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
break;
case SENSOR_ORIENTATION_INVERSE_DEGREES:
mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
break;
}
mMediaRecorder.prepare();
}
private File getVideoFilePath(Context context) {
File appDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (!appDir.isDirectory()) {
appDir.mkdirs();
}
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "VIDEO_" + timestamp + ".mp4";
File videoFile = null;
try {
videoFile = File.createTempFile(prepend, ".mp4", appDir);
} catch (IOException e) {
e.printStackTrace();
}
return videoFile;
}
private void startRecordingVideo() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
setUpMediaRecorder();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
List<Surface> surfaces = new ArrayList<>();
// Set up Surface for the camera preview
Surface previewSurface = new Surface(texture);
surfaces.add(previewSurface);
mPreviewBuilder.addTarget(previewSurface);
// Set up Surface for the MediaRecorder
Surface recorderSurface = mMediaRecorder.getSurface();
surfaces.add(recorderSurface);
mPreviewBuilder.addTarget(recorderSurface);
mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull final CameraCaptureSession cameraCaptureSession) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPreviewSession = cameraCaptureSession;
updatePreview();
mIsRecordingVideo = true;
startTime = SystemClock.uptimeMillis();
mChronometer.setVisibility(View.VISIBLE);
customHandler.postDelayed(updateTimerThread, 0);
mRecordButton.setImageResource(R.drawable.ic_video_stop);
mMediaRecorder.start();
mCheckPoint.setEnabled(true);
}
});
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException | IOException e) {
e.printStackTrace();
}
}
private void closePreviewSession() {
if (mPreviewSession != null) {
mPreviewSession.close();
mPreviewSession = null;
}
}
#SuppressLint("ResourceType")
private void stopRecordingVideo() {
mIsRecordingVideo = false;
customHandler.removeCallbacks(updateTimerThread);
mRecordButton.setImageResource(R.drawable.ic_video);
if(mMediaRecorder!=null) {
try {
mMediaRecorder.stop();
} catch (RuntimeException e) {
e.printStackTrace();
}
mMediaRecorder.reset();
}
}
static class CompareSizesByArea implements Comparator<Size> {
#Override
public int compare(Size lhs, Size rhs) {
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
#Override
protected void onDestroy() {
customHandler.removeCallbacks(updateTimerThread);
}
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
Change aspect ratio values in AutoFitTextureView class or use Textureview instead of AutoFitTextureview.
Hi guys I've got an error in this.printPreviewDialog1 (the project no contains a definition for printviewdialog and no extension for printviewdialog accepting a first argument of type Project print. I already added up the reference System.Printing and System.Windows.Form.Data Visualization. What I miss? Thanks
public partial class Print : Form
{
public Print()
{
InitializeComponent();
this.button1.Click += button1_Click;
this.printDocument1.PrintPage += printDocument1_PrintPage;
}
private void Print_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.printPreviewDialog1.Document = this.printDocument1;
this.printPreviewDialog1.Document.DocumentName = "PictureTextDesignerFile1";
this.printPreviewDialog1.Size = new Size(800, 600);
this.printPreviewDialog1.ShowDialog();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
float neededWidth = 700 ;
float neededHeight = 1100;
float availableWidth = 700;
float availableHeight = 1100;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
Bitmap bmpPrint = null;
try
{
double multiplier = neededWidth / neededHeight;
double dblRef = availableWidth / availableHeight;
float zoom = 1;
if (multiplier >= dblRef)
{
zoom = availableWidth / neededWidth;
}
else
{
zoom = availableHeight / neededHeight;
}
bmpPrint = new Bitmap(this.Width, this.Height);
bmpPrint.SetResolution(300, 300);
this.DrawToBitmap(bmpPrint, new Rectangle(0, 0, bmpPrint.Width, bmpPrint.Height));
e.Graphics.Clip = new Region(e.MarginBounds);
e.Graphics.DrawImage(bmpPrint, e.MarginBounds.Left, e.MarginBounds.Top, Math.Min(neededWidth * zoom, availableWidth), Math.Min(neededHeight * zoom, availableHeight));
e.Graphics.Clip.Dispose();
}
catch
{
}
finally
{
if ((bmpPrint != null))
{
bmpPrint.Dispose();
bmpPrint = null;
}
}
}
I try to create a class of object (picturebox), then calling it my main code to create other picturebox from a menu of different picturebox. I want to fix them on a panel to draw shcema or organigrams.
thanks
class _createpicture
{
public int p;
public int p_2;
PictureBox pictureBox2 = new PictureBox();
Panel panel1 = new Panel();
Color color = new Color();
Pen pen = new Pen(Color.Black, 1);
Bitmap flag = new Bitmap(40, 30);
ContextMenu cm = new ContextMenu();
public int x;
public int y;
public _createpicture () {
pictureBox2.Size = new Size(40, 30);
pictureBox2.MouseClick += new MouseEventHandler(pic_mouseclick);
pictureBox2.MouseMove += new MouseEventHandler(pic_mouseMouve);
MenuItem item_1 = cm.MenuItems.Add("Définir");
MenuItem item_2 = cm.MenuItems.Add("Supprimer");
item_1.Click += new EventHandler(item_1_Click);
item_2.Click += new EventHandler(item_2_Click);
}
private void item_1_Click(object sender, EventArgs e)
{
var myForm = new Form2();
myForm.Show();
}
private void item_2_Click(object sender, EventArgs e)
{
pictureBox2.Dispose();
}
public void _create_picture(PictureBox pictureBox2, int p, int p_2, Color color)
{
}
public void _add(Panel panel1, int p, int p_2, Color color)
{
panel1.Controls.Add(pictureBox2);
pictureBox2.BackColor = color;
Graphics flagGraphics = Graphics.FromImage(flag);
flagGraphics.DrawRectangle(pen, p, p_2, 20, 10);
flagGraphics.FillRectangle(Brushes.Red, p, p_2, 40, 30);
pictureBox2.Image = flag;
panel1.Controls.Add(pictureBox2);
}
public void pic_mouseclick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
pictureBox2.ContextMenu = cm;
}
if (e.Button == MouseButtons.Left)
{
x = e.X;
y = e.Y;
}
}
public void pic_mouseMouve(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pictureBox2.Left += (e.X - x);
pictureBox2.Top += (e.Y - y);
}
}}
public partial class Form1 : Form
{
_createpicture _createpicture10 = new _createpicture();
.
.
.
.
if (radioButton2.Checked) {
_createpicture10._create_picture(picturebox10, e.X, e.Y, Color.Red); _createpicture10._add(this.panel1, e.X, e.Y, Color.Red);
}
}
I have created a simple client/server app and it works great (1MB/s which is max speed i set for server to send) when i run in locally or under Lan network. But when i try to run it in one of my Dedicate Server/VPS my download speed become slow.
I am using CentOS on servers and Mono for running it, Mono version is 2.10.2 and CentOs is 64bit version. Created using framework 4.
Speed test:
Local: 1MB
Lan: 1MB
Running server on CentOS: 0~10~20 KB
My connection speed is 2Mb or ~250KB. It will give me full speed some times. But very rare and i cant see why it give my full speed sometimes and sometimes no speed at all or why sometimes only 10KB and other times only 20KB. Also, i am running client part on my Win7 Desktop. Here is code for server and client part:
Server:
class Program
{
private static BackgroundWorker _ListeningWorker;
private static BackgroundWorker _QWorker;
private static System.Net.Sockets.Socket _Server;
private static List<System.Net.Sockets.Socket> ConnectedClients = new List<System.Net.Sockets.Socket>();
static void Main(string[] args)
{
Program._ListeningWorker = new BackgroundWorker();
Program._ListeningWorker.WorkerSupportsCancellation = true;
Program._ListeningWorker.DoWork += _ListeningWorker_DoWork;
Program._QWorker = new BackgroundWorker();
Program._QWorker.WorkerSupportsCancellation = true;
Program._QWorker.DoWork += _QWorker_DoWork;
Program.Start();
while (true)
{
Console.Clear();
Console.WriteLine("1.0.0.1");
Console.WriteLine(Program.ConnectedClients.Count.ToString());
System.Threading.Thread.Sleep(1000);
}
}
public static bool Start()
{
if (!Program._ListeningWorker.IsBusy)
{
Program._Server = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8081);
Program._Server.Bind(ipLocal);
Program._Server.Listen(10);
Program._ListeningWorker.RunWorkerAsync();
Program._QWorker.RunWorkerAsync();
}
return true;
}
private static void _ListeningWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!Program._ListeningWorker.CancellationPending)
{
if (Program._Server.Poll(10, SelectMode.SelectRead))
{
lock (ConnectedClients)
{
Program.ConnectedClients.Add(Program._Server.Accept());
}
}
System.Threading.Thread.Sleep(1);
}
Program._Server.Close();
}
private static void _QWorker_DoWork(object sender, DoWorkEventArgs e)
{
byte[] array = new byte[1024];
Random random = new Random();
while (!Program._QWorker.CancellationPending)
{
if (ConnectedClients.Count > 0)
{
System.Net.Sockets.Socket[] st;
lock (ConnectedClients)
{
st = new System.Net.Sockets.Socket[Program.ConnectedClients.Count];
ConnectedClients.CopyTo(st);
}
foreach (System.Net.Sockets.Socket ser in st)
{
random.NextBytes(array);
try
{
ser.BeginSend(array, 0, array.Length, SocketFlags.None, (AsyncCallback)delegate(IAsyncResult ar)
{
try
{
ser.EndSend(ar);
}
catch (Exception)
{
iDissconnected(ser);
}
}, null);
}
catch (Exception)
{
iDissconnected(ser);
}
}
}
System.Threading.Thread.Sleep(1);
}
Program._Server.Close();
}
internal static void iDissconnected(System.Net.Sockets.Socket client)
{
lock (ConnectedClients)
for (int i = 0; i < ConnectedClients.Count; i++)
if (ConnectedClients[i].Equals(client))
{
ConnectedClients.RemoveAt(i);
i--;
}
}
}
Client:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter IP Address: ");
string Address = Console.ReadLine();
Console.WriteLine();
ushort Port = 8081;
System.Net.Sockets.Socket Client;
Client = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(Address, (int)Port);
Console.WriteLine("Connected");
int p = 0;
int t = Environment.TickCount;
while (true)
{
if (Client.Available > 0)
{
byte[] z = new byte[1024];
int r = Client.Receive(z); ;
p += r;
}
else
{
System.Threading.Thread.Sleep(10);
}
if (Environment.TickCount - t >= 1000)
{
t = Environment.TickCount;
Console.WriteLine(Program.FormatFileSizeAsString(p) + " Readed,");
p = 0;
}
}
}
public static string FormatFileSizeAsString(int len)
{
if (len < 750 && len > 0)
return "0.0 B ~";
string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
int i;
double dblSByte = len;
for (i = 0; (int)(len / 1024) > 0; i++, len /= 1024)
dblSByte = len / 1024.0;
return String.Format("{0:0.0} {1}", dblSByte, Suffix[i]);
}
}
Thanks all, Please tell me what you think about possible problems.
It was some sort of limitation by ISP per each connection.
Solving was funny. I used to send a HTTP Header before my request and ISP increased my speed because of that.