Java的Socket实现通信

原创
2017/05/09 15:21
阅读数 147

_java结合Socket实现通信, 具体用socket实现简单的聊天 现在HIA没有思路

Socket套接字

服务端

public class ServerSocketDemo {
	public static void main(String[] args) throws IOException {
		System.out.println("socket 服务端启动...");
		ServerSocket serverSocket = new ServerSocket(2017);
		while(true){
			Socket s = serverSocket.accept();
			socketThread thread = new socketThread(s);
			thread.start();
		}
	}
}

客户端

public class ClientSocket {

	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		
		Socket scoket = new Socket(InetAddress.getLocalHost().getHostAddress(), 2017);
		OutputStream outputStream = scoket.getOutputStream();
		OutputStreamWriter writer = new OutputStreamWriter(outputStream);
		writer.write("helloWorld");
		writer.flush();
		writer.close();
		
	}
}

thread

public class socketThread extends Thread {

	Socket element = null;
	public socketThread(Socket s){
		this.element = s;
	}
	@Override
	public void run() {
		InputStream input;
		
				try {
					input = element.getInputStream();
					InputStreamReader reader = new InputStreamReader(input);
					BufferedReader bReader = new BufferedReader(reader);
					System.out.println(element.toString()+bReader.readLine());
					//释放资源 关闭连接
					bReader.close();
					reader.close();
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	}

}

运行结果

输入图片说明

好吧今天就到这。。。

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部