客户端代码:
package com.kaige123.net01;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*凯哥
*/
public class Client {
public static void main(String[] args) throws Exception {
// 如果对方服务器不存在就会报错
Socket socket = new Socket("127.0.0.1", 8080);
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
output.write("你好服务器,我是凯哥,你还记得我吗?".getBytes());
output.flush();//赶紧把内容输出到对方
byte[] b=new byte[1024];
int len=input.read(b);
System.out.println("服务器说:"+new String(b,0,len));
output.close();
input.close();
socket.close();
}
}
服务端代码:
package com.kaige123.net01;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*凯哥
*/
public class Server{
public static void main(String[] args) throws Exception {
// 如果都被占用 那就会抛异常
// 建立好一个服务端 监听8080端口
ServerSocket server = new ServerSocket(8080);
// 等待客户端来连接服务器
Socket socket = server.accept(); //代码运行到这句就会卡主 堵塞 等待
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
byte[] b = new byte[1024 * 5];
int len = input.read(b);
String s = new String(b, 0, len);
System.out.println(s);
s = "你好凯哥,我是从东莞回来的美女!!";
output.write(s.getBytes());
output.close();
input.close();
socket.close();
}
}