客户端
package cn.usts.edu.lesson02;
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;
// 1*要知道服务器的地址
try {
InetAddress ServerIP = InetAddress.getByName("127.0.0.1");
int port=9999;
socket = new Socket(ServerIP, port);//建立一个插座
os = socket.getOutputStream();
os.write("第一个tcp聊天室".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端
package cn.usts.edu.lesson02;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
// 1*首先得先有一个地址,让被人连过来
try {
// serverSocket默认开启服务的主机,当前的ip地址为服务器地址,所以只需要个端口号
serverSocket = new ServerSocket(9999);
while (true){
socket = serverSocket.accept();// 监听 监听接受到socket就是连接上来的socket
inputStream = socket.getInputStream();
// 读取消息
/* 获取超过1024个字节的中文就容易产生乱码
InputStream inputStream = socket.getInputStream();
byte[] buffer =new byte[1024];
int len;
// 从输入流读取一些字节数,并将它们存储到缓冲区b 。 实际读取的字节数作为整数返回。
while ((len=inputStream.read(buffer))!=-1){
String msg = new String(buffer, 0, len);
System.out.println(msg);
} */
byteArrayOutputStream = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len=inputStream.read(buffer))!=-1){
byteArrayOutputStream.write(buffer,0,len);
}
System.out.println(byteArrayOutputStream.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
if (byteArrayOutputStream!=null){
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.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();
}
}
}
}