客户端
1.通过Socket连接服务器
2.发送消息
Java
package com.jfy.webCode01;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//Tcp客户端
public class TcpClient {
public static void main(String[] args) {
Socket socket = null;
OutputStream OS = null;
//获得服务端的地址
try {
InetAddress ServerIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//创建一个socket连接
socket = new Socket(ServerIP,port);
//发送消息
OS = socket.getOutputStream();
OS.write("我好困我好困我好困我好困".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
if (OS!=null){
try {
OS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
服务器
1.建立服务的端口ServerSocket
2.通过Accept()等待客户的连接
3.接收用户的消息
Java
package com.jfy.webCode01;
//Tcp服务端
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream IS = null;
ByteArrayOutputStream BAOS = null;
try {
//服务端需要有一个地址
serverSocket = new ServerSocket(9999);
while (true) {
//等待客户端连接
accept = serverSocket.accept();
//接受消息
IS = accept.getInputStream();
//管道流
BAOS = new ByteArrayOutputStream();
byte[] buffer = new byte[1048];
int lenth;
while ((lenth = IS.read(buffer)) != -1) {
BAOS.write(buffer, 0, lenth);
}
System.out.println(BAOS.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
if (IS != null) {
try {
IS.close();
} catch (IOException e) {
e.printStackTrace();
}
if (BAOS != null) {
try {
BAOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}