客户端代码:
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 {
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();
}
}
|