客户端
package com.zhl.nett;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClient1 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os= null;
try {
InetAddress severIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(severIP, port);
os =socket.getOutputStream();
os.write("你好,11欢迎学习网络编程".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.zhl.nett;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpSever1 {
public static void main(String[] args) {
ServerSocket serverSocket1 = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket1 = new ServerSocket(9999);
while (true){
socket = serverSocket1.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(baos!=null) {
try {
baos.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(serverSocket1!=null){
try {
serverSocket1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}