网络编程路线建立的建立大部分使用的都是TCP,所以这里就是用TCP连接,其实实现多个客户端之间的交互其实不是很难,服务器只是一个中转站,我们需要注意的是把每一个客户端端口的连接都放到一个子线程去进行。不然会报错。
1、客户端 Client1.java
/**
* CopyRight 2015 CodeLansus' IDE
*
* All right servered
* created on 2015-9-25 上午8:43:58
* By lansus
*/
public class Clientschat {
private static DataOutputStream dos;
private static DataInputStream dis;
public static void main(String []args) throws UnknownHostException, IOException{
Socket client=new Socket("localhost",5658);
dos=new DataOutputStream(client.getOutputStream());
dis=new DataInputStream(client.getInputStream());
while(true){
System.out.println("请输入");
Scanner sc=new Scanner(System.in);
String msg=sc.next();
dos.writeUTF(msg);
}
}
2、客户端2 Client2
/**
* CopyRight 2015 CodeLansus' IDE
*
* All right servered
* created on 2015-9-25 涓婂崍8:43:58
* By lansus
*/
public class Clientschat2 {
private static String msg="seconds person";
private static char[] cbuf=new char[1024];
public static void main(String []args) throws UnknownHostException, IOException{
final Socket client;
client =new Socket("localhost", 5657);
DataInputStream dis=new DataInputStream(client.getInputStream());
while(true){
System.out.println(dis.readUTF());
}
}
}
3 服务端
/**
* CopyRight 2015 CodeLansus’ IDE
*
* All right servered
* created on 2015-9-24 涓嬪崍5:42:44
* By lansus
*/
public class Servers {
private static ServerSocket server;
private static Socket socket;
private static DataOutputStream dos1;
private static DataInputStream dis1;
private static DataOutputStream dos2;
private static DataInputStream dis2;
public static void main(String []args) throws IOException{
//
Runnable client1_runble=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
server = new ServerSocket(5658);
socket=server.accept();
dos1=new DataOutputStream(socket.getOutputStream());
dis1=new DataInputStream(socket.getInputStream());
while(true){
String msg=dis1.readUTF();
dos2.writeUTF(msg);
// System.out.print(msg);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 鑾峰緱鏁版嵁
* @throws IOException
*/
};
Runnable client2_runble=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
ServerSocket server1;
try {
server1 = new ServerSocket(5657);
Socket socket1=server1.accept();
dos2=new DataOutputStream(socket1.getOutputStream());
dis2=new DataInputStream(socket1.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread client1=new Thread(client1_runble);
Thread client2=new Thread(client2_runble);
client1.start();
client2.start();
}
}
这段简单的代码实现对功能是客户端1 向客户端2发送信息,多几个客户安就是类似的增加几个子线程就行了