TCP实现聊天
客户端
public class TestClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream outputStream = null;
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(serverIP,port);
outputStream = socket.getOutputStream();
outputStream.write("你好,我是小周周~".getBytes());
}catch (Exception e){
e.printStackTrace();
}finally {
if (null != outputStream){
try {
outputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (null != socket){
try {
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
服务端
public class TestServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try{
serverSocket = new ServerSocket(9999);
while (true){
socket = serverSocket.accept();
inputStream = socket.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer,0,len);
}
System.out.println(byteArrayOutputStream.toString());
}
}catch(Exception e){
e.printStackTrace();
}finally {
if (null != byteArrayOutputStream){
try {
byteArrayOutputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (null != inputStream){
try {
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (null != socket){
try {
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (null != serverSocket){
try {
serverSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}