文章目录
TCP
建立连接客户端给服务器发送
客户端
//客户端
public class TcpClient {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
InetAddress address = InetAddress.getByName("127.0.0.1");
//连接到服务端,通过ip和端口
socket = new Socket(address, 9999);
//发送信息
os = socket.getOutputStream();
os.write("看我传过去...".getBytes());
} catch (IOException 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();
}
}
}
}
}
服务端
//服务端
public class TcpServer {
public static void main(String[] args) {
ServerSocket socket = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//服务端的端口
socket = new ServerSocket(9999);
//接收连接
accept = socket.accept();
//读取收到,写出去
is = accept.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 (IOException e) {
e.printStackTrace();
} finally {
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null){
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
如有不对的地方欢迎指出,共同进步!