给你一个我写的示例,用的是基于TCP的Socket技术,你锻炼一下,改一改,不会改再找我!
客户端:
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class TcpClient {
public static void main(String[] args) throws Exception
{
//创建客户端Socket服务,并且制定主机和duank
Socket s = new Socket("192.168.1.104",10002);//连接固定的主机和端口
//为了发送数据,获取Socket中的输入输出流
OutputStream out = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = null;
//读取服务器发过来的数据
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
while((line = br.readLine())!=null)
{
out.write(line.getBytes());
if("886".equals(line))
break;
int len = in.read(buf);
String content = new String(buf,0,len);
System.out.println("Server:"+content);
}
s.close();
}
}
服务器:
/*
* 需求分析:
* 使用TCP协议,写服务器端。做到服务器能收到客户端的信息,也能向客户端发送信息
* */
package JavaNetProgramming;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class TcpServer {
public static void main(String[] args) throws Exception
{
//建立服务器的Socket服务,并且监听一个端口
ServerSocket ss = new ServerSocket(10002);
Socket s = ss.accept();
InputStream is = s.getInputStream();
//从服务器端向客户端发送数据
OutputStream out = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = null;
while(true)
{
//通过accept()方法获得客户端传过来的Socket对象
// System.out.println("getByNanme():"+s.getInetAddress());
System.out.print("getHostAddress():"+s.getInetAddress().getHostAddress());
//获取客户端发过来的数据,就要使用客户端对象的读取流来读取数据
byte[] buf = new byte[1024];
int len = is.read(buf);//把流中数据读到字节数组中
String content = new String(buf,0,len);
System.out.println(" "+content);
if("886".equals(content))
break;
while((line = br.readLine())!=null)
{
out.write(line.getBytes());
break;
}
}
s.close(); //循环内有判断语句,这句话才不出错
ss.close();
}
}
温馨提示:内容为网友见解,仅供参考