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();
接收消息