java服务器向客户端发消息_java一个简单的客户端向服务端发送消息
java一個簡單的客戶端向服務端發送消息
客戶端代碼:
package com.chenghu.tcpip;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//客戶端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket=null;
OutputStream os=null;
try {
//服務器ip
InetAddress serverIP=InetAddress.getByName("127.0.1");
//端口
int port=9999;
//創建鏈接
socket=new Socket(serverIP,port);
//發送消息 io流
os=socket.getOutputStream();
os.write("你好!".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {//關閉資源
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服務端代碼:
package com.chenghu.tcpip;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
//服務端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream bas=null;
try {
//需要 一個地址
serverSocket= new ServerSocket(9999);
while(true) {
//等待客戶端連接
socket = serverSocket.accept();
//讀取客戶端的消息
is = socket.getInputStream();
//管道流
bas = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
bas.write(buffer, 0, len);
}
System.out.println(bas.toString());
}
} catch (IOException ex) {
ex.printStackTrace();
}finally {//關閉資源
if (bas != null) {
try {
bas.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
總結一下 :
客戶端:
連接服務器Socket
發送消息
服務器
建立服務端口
等待用戶連接accept();
接收消息
總結
以上是生活随笔為你收集整理的java服务器向客户端发消息_java一个简单的客户端向服务端发送消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EXCEL利用VBA把汉字转拼音(李晓锋
- 下一篇: 安卓游戏广告加速插件_游戏加速器(强烈推