现在的位置: 首页 > 综合 > 正文

scoket网络通信收发消息

2017年12月20日 ⁄ 综合 ⁄ 共 1711字 ⁄ 字号 评论关闭

              先来看客户端代码:

               

package client.sendReceive;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
 * 向服务端程序发送消息,
 * @author kevin liu<wenhaoliu117@gmail.com>
 *
 */
public class SenderSocket {
	private String ip;
	private int port;

	/**
	 * 初始化
	 * @param ip 服务端socket
	 * @param port 服务端机器的ip地址
	 */
	public SenderSocket(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	/**
	 * 
	 * @param msg 
	 */
	public void sendMsg(String msg) {
		try {
			Socket client = new Socket(ip, port);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					client.getOutputStream()));
			writer.write(msg.trim());
			writer.close();
			client.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

服务端代码:

 

package server.sendReceive;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * 服务端,用于接收客户端的信息
 * @author kevin liu<wenhaoliu117@gmail.com>
 *
 */
public class ReceiverSocket {
	private int port;//端口号,在配置文件中
	public ReceiverSocket(int port){
		this.port = port;
	}
	public void startListening(){
		Thread listenThread = new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					ServerSocket servSocet = new ServerSocket(port);
					Socket socket = null;
					BufferedReader br = null;
					String tmp1 = null;
					String tmp2 = null;
					while(true){
						//等待建立连接
						socket = servSocet.accept();
						//读取数据,多线程的话,把new 一个thread,把socet传给它
						br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						StringBuffer sb = new StringBuffer();
						String tmp = null;
						while((tmp=br.readLine())!=null){
							sb.append(tmp);
						}
						br.close();
						if(socket !=null ){
							socket.close();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		listenThread.start();
	}
}

以上是工作中遇到scoket通信接受消息的实例代码,如有错误恳请指教~~~

抱歉!评论已关闭.