Socket 学习

 这两个月要做一个Android远程控制PC的一个project,昨天才分析出思路,先做基本的,socket连接,到图书馆找socket编程的书,结果《Thinking in java》里面没见socket,不知道是我英文不好还是怎样,但当时就剩下一本英文版的。只能另外找了一本,我看讲得确实很不错。就照着写了一遍

1,建立服务器端,分为5步:

第一步:创建ServerSocket对象

ServerSocket server = new ServerSocket(port,queueLength);


 

第二步:通过ServerSocket将服务器与端口绑定,监听客户机进行的连接

Socket connection = server.accept();


 

这条语句返回一个Socket对象

第三步:获得OutputStream和InputStream对象

ObjectInputStream input = new ObjectInptStream(connection.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());



 

第四步:服务器和客户端通过InputStream和OutputStream对象通信

 

第五步:关闭连接

Server代码

package com.zph.control;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * 2011-10-23 14:57
 * 
 * */

public class Server extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3956199261211237769L;
	private JTextField enterField;
	private JTextArea displayArea;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	private ServerSocket server;
	private Socket connection;
	private int counter = 1;
	
	private int port = 5000;
	
	public int getPort() {
		return this.port;
	}

	public  void setPort(int port) {
		this.port = port;
	}

	public Server() {
		super("server");
		Container container = this.getContentPane();
		enterField = new JTextField();
		enterField.setEnabled(false);
		
		this.enterField.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				sendData(e.getActionCommand());
				enterField.setText("");
			}
			
			//end inner class
		});
		container.add(enterField, BorderLayout.NORTH);
		
		displayArea = new JTextArea();
		container.add(new JScrollPane(displayArea), BorderLayout.CENTER);
		
		
		setSize(300,500);
		setVisible(true);
	}

	protected void sendData(String message) {
		
		try {
			this.output.writeObject("SERVER >>> "+ message);
			this.output.flush();
			displayArea.append("\nSERVER>>>"+message);
		} catch (IOException e) {
			displayArea.append("\n ERROR>>>"+message);
		}
	}
	
	public void runServer(){
		
		try {
			//step 1
			server = new ServerSocket(port,10);     
		} catch (IOException e) {
			displayArea.append("\nServer IO Exception "+e.toString());
		}
		
		while(true){
			//step 2
			waitForConnection();
			//step 3
			getStream();
			//step 4
			processConnection();
			//step 5
			closeConnection();
			
			++counter;
		}
		
	}

	

	private void waitForConnection() {
		displayArea.setText("wait for connection\n");
		
		try {
			connection = server.accept();     
			displayArea.append("connection"+counter
					+"recevied from:" 
					+connection.getInetAddress().getHostName());
		} catch (IOException e) {
			displayArea.append("\n"+e.toString());
		}
		
		
	}
	

	private void getStream() {
		try {
			output = new ObjectOutputStream(connection.getOutputStream());
			output.flush();
			
			input =new ObjectInputStream( connection.getInputStream());
			
			displayArea.append("\nGot I/O streams\n");
		} catch (IOException e) {
			displayArea.append("\n"+e.toString());
		}
	}

	private void processConnection() {
		String message = "SERVER>>> Connection successful";
		
		try {
			output.writeObject(message);
			output.flush();
		} catch (IOException e) {
			displayArea.append("\n"+e.toString());
		}
		
		
		enterField.setEnabled(true);
		
		do{
			try {
				message = (String) input.readObject();

				displayArea.append("\n"+message);
				displayArea.setCaretPosition(displayArea.getText().length());

			} catch (IOException e) {
				displayArea.append("\nIOException"+e.toString());
				
			} catch (ClassNotFoundException e) {
				displayArea.append("\nClassNotFound Exception");
			}
			
		}while(!message.trim().equalsIgnoreCase("CLIENT>>>TERMINATE"));
		
	}
	
	private void closeConnection() {
		displayArea.append("\nUser terminated connection");
		enterField.setEnabled(false);
		try {
			output.close();
			input.close();
			connection.close();
			
		} catch (IOException e) {
			displayArea.append("\n"+e.toString());
		}
		
	}
	
	public static void main(String[] args) {
		Server PCServer = new Server();
		
		PCServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		PCServer.runServer();
	}
}


 

2,建立客户端,分为四步:

第一步:创建一个Socket对象用来连接到服务器上

Socket connection = new Socket(serverAddress , port);

第二步:用Socket的getInputStream方法和getOutputStream方法分别用于获得与Socket 相关联的InputStream和OutputStream的引用,

第三步:客户端与服务端通过InputStream和OutputStream 对象通信的处理

第四步:关闭连接

Client代码:

package com.zph.control;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;


/**
 * 2011-10-23 15:53
 * 
 * */
public class Client extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3221172809627731102L;
	private JTextField enterField;
	private JTextArea displayArea;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	private String message = "";
	private String chatServer;
	private Socket client;

	private int port = 5000;

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public Client(String host) {
		super("client");

		chatServer = host;

		Container container = this.getContentPane();

		enterField = new JTextField();
		enterField.setVisible(true);

		enterField.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				sendData(e.getActionCommand());
				enterField.setText("");
			}

			// end inner class
		});// end addActionListener

		container.add(enterField, BorderLayout.NORTH);

		displayArea = new JTextArea();
		container.add(new JScrollPane(displayArea), BorderLayout.CENTER);

		this.setSize(300, 500);
		this.setVisible(true);

	}

	protected void sendData(String message) {
		try {
			output.writeObject("CLIENT>>>" + message);
			
			output.flush();
			displayArea.append("\nCLIENT>>>" + message);

		} catch (IOException e) {
			displayArea.append("\nERROR wirte Object");
		}

	}

	public void runClient() {

		// step 1 ,create a socket to make connection
		connectToServer();

		//step 2 , get inputStream and outputStream
		getStreams();

		// step 3 ,process connection
		proccessConnection();

		// step 4 ,close connections
		closeConnection();
	}

	private void connectToServer() {
		try {
			displayArea.setText("Attempting connection\n");

			client = new Socket(InetAddress.getByName(chatServer), port);

			displayArea.append("connection to "
					+ client.getInetAddress().getHostName());
		} catch (UnknownHostException e) {
			displayArea.append("\nERROR unKnownHost");
		} catch (IOException e) {
			displayArea.append("\n" + e.toString());
		}

	}

	private void getStreams() {
		try {
			output = new ObjectOutputStream(client.getOutputStream());
			output.flush();
			input = new ObjectInputStream(client.getInputStream());

		} catch (IOException e) {
			displayArea.append("\n"+e.toString());
		}

	}

	private void proccessConnection() {
		enterField.setEnabled(true);
		
		do{
			try {
				message = (String) input.readObject();
				displayArea.append("\n"+message);
				
				displayArea.setCaretPosition(
						displayArea.getText().length());
			
			} catch (IOException e) {
				displayArea.append("\n"+e.toString());
			} catch (ClassNotFoundException e) {
				displayArea.append("\n class not found");
			}
			
			
		}while(!message.trim().equalsIgnoreCase("SERVER>>>TERMINATE"));
	
	}

	private void closeConnection() {
		displayArea.append("\nClosing connection");
		try {
			output.close();
			input.close();
			client.close();
		} catch (IOException e) {
			displayArea.append("\n"+e.toString());
		}
		
	}
	
	public static void main(String[] args) {
		Client PCClient = new Client("127.0.0.1");
		
		PCClient.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		PCClient.runClient();
	}
}


 

 

 


回到需求,android作为控制端,PC作为受控端,连接的时候(我个人觉得)如果是在局域网,只要设置一下IP和端口,一样可以用这个办法连,如果是连上了Internet,我真不知道会不会成功,感觉设置好了IP和端口也行。

昨天下载了一个网灵一号,做的真好,画面居然还能那么清晰。

android部分的代码本来我要写出来了,可是5点钟的时候让我真的受不了了,我又要发一下牢骚,这世道这么会有这么多邪恶的人,大白天的对人家女生那么无理,人家是去学车的,你作为教练也算是老师,有句话怎么说的:……

女生学车千万别一个人去!




 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值