//客户端代码
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
public class Client
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("127.0.01", 1100);//创建套接字,制定服务器地址
System.out.println("连接成功");
OutputStream out = client.getOutputStream();
String message = "服务器你好我是客户端";
out.write(message.getBytes());
InputStream in = client.getInputStream();
byte[] bt = new byte[1024];
int len = in.read(bt);
String data = new String(bt,0,len);
System.out.println("服务器发来消息: " +data);
client.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//服务器端代码
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
public class Server
{
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(1100);//创建服务器套接字
System.out.println("服务器启动成功,等待用户接入。。。");
Socket client = server.accept();//等待用户接入
System.out.println("有客户端接入,客户端IP: " +client.getInetAddress());//获取客户端地址
InputStream in = client.getInputStream();
byte[] bt = new byte[1024];
int len = in.read(bt);
String data = new String(bt,0,len);
System.out.println("客户端发来消息: " +data);
OutputStream out = client.getOutputStream();
String message = "这里是服务器,欢迎光临";
out.write(message.getBytes());
client.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}