本文主要是介绍JavaSocket简单通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以下介绍:简单的socket发送消息,服务的Server 相互 客户端Client,进行简单的传递消息:
服务端代码:
package test;import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;public class Server {/*** 服务器连接的Socket*/public static ServerSocket cServerSocket;/*** 连接 */public static Socket cSocket;/*** 端口 */public static final int PORT = 8888;public static void main(String[] args) {DataInputStream dis = null;DataOutputStream dos = null;try {cServerSocket = new ServerSocket(PORT);while (true) {System.out.println("正在等待客户连接...");// 这里处于等待状态,如果没有客户端连接,程序不会向下执行cSocket = cServerSocket.accept();dis = new DataInputStream(cSocket.getInputStream());dos = new DataOutputStream(cSocket.getOutputStream());// 读取数据String clientStr = dis.readUTF();String msg = "已收到信息:"+clientStr;// 写出数据dos.writeUTF(msg);System.out.println(msg);System.out.println("---客户端信息打印,IP:"+ cSocket.getInetAddress()+ " Prot:" + cSocket.getPort());}} catch (IOException e) {e.printStackTrace();} finally {try {if (dis != null) {dis.close();}if (dos != null) {dos.close();}} catch (IOException e) {e.printStackTrace();}}}
}
客户端代码:
private Socket cSocket;
// 服务器server/IP地址(当前PC的IP地址)
private final String ADDRESS = "192.168.8.2";
// 服务器端口
private final int PORT = 8888;
cThread = new Thread() {
@Override
public void run() {super.run();DataInputStream dis = null;DataOutputStream dos = null;try {// 阻塞函数,正常连接后才会向下继续执行cSocket = new Socket(ADDRESS, PORT);dis = new DataInputStream(cSocket.getInputStream());dos = new DataOutputStream(cSocket.getOutputStream());// 向服务器写数据dos.writeUTF("hello socket...");// 读取服务器发来的数据cContent += dis.readUTF();} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (dis != null) {dis.close();}if (dos != null) {dos.close();}} catch (IOException e) {e.printStackTrace();}}; cThread.start();
运行效果:
谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问,
刘德利CSDN博客, http://blog.csdn.net/u011967006
这篇关于JavaSocket简单通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!