Java使用TCP聊天程序

前面使用了UDP进行通信的聊天程序

现在做一个用TCP进行通信的聊天程序

原理:

ServerSocket Socket

1.开一个线程监听端口,准备接收消息

2.不断接受消息发送到目的端口

P.S.因为TCP是面向连接的所以中间要注意先后顺序,代码写得有点乱

 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner; /**
* 聊天程序
* TCP实现
* 开一个线程监听一个端口,接收消息
* @author GXF
*
*/
public class TcpChatWindow {
private int destPort; //目的端口
private int listenPort; //监听端口
private Socket socketToSendMessage; //发送消息的socket public TcpChatWindow(int destPort, int listenPort){
this.destPort = destPort;
this.listenPort = listenPort; //init
init();
} /**
* 接收消息线程
* @author GXF
*
*/
class ReceiveMessageThread implements Runnable{
//接收消息socket
private ServerSocket receiveMessageSocket; @Override
public void run() {
//init
init();
while(true){
try {
Socket clientSocket = receiveMessageSocket.accept();
InputStream inputStreamOfClientSocket = clientSocket.getInputStream();
byte buff[] = new byte[1024];
int lengthOfMessage = -1;
StringBuilder sb = new StringBuilder();
//read message
while((lengthOfMessage = inputStreamOfClientSocket.read(buff)) > 0){
sb.append(new String(buff, 0, lengthOfMessage));
}//while
//输出消息到控制台
System.out.println(sb.toString());
//关闭socket
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 对线程进行初始化
*/
public void init(){
try {
receiveMessageSocket = new ServerSocket(listenPort);
} catch (IOException e) {
e.printStackTrace();
}
} } //初始化操作
private void init(){ //start ReceiveMessageThread
Thread receiveMessageThread = new Thread(new ReceiveMessageThread());
receiveMessageThread.start();
//input message and send message
while(true){
Scanner scanner = new Scanner(System.in);
String messageToSend = scanner.nextLine();
// getSocketToSendMessage();
sendMessage(messageToSend);
scanner.close();
} } /**
* 向对方发送消息
* @param message
*/
public void sendMessage(String message){
try {
Socket socketToSendMessage = new Socket(InetAddress.getByName("127.0.0.1"), destPort);
OutputStream outputStreamOfClientSocket = socketToSendMessage.getOutputStream();
byte bytesOfMessage[] = message.getBytes();
outputStreamOfClientSocket.write(bytesOfMessage);
socketToSendMessage.close();
} catch (IOException e) {
e.printStackTrace();
}
} //获取发送消息的socket
public Socket getSocketToSendMessage(){
if(socketToSendMessage == null){
try {
socketToSendMessage = new Socket(InetAddress.getByName("127.0.0.1"), destPort);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return socketToSendMessage;
} public static void main(String args[]){
if(args.length != 2){
System.out.println("usage: java TcpChatWindow destport listenport");
return;
}
int destPort = Integer.valueOf(args[0]);
int listenPort = Integer.valueOf(args[1]); TcpChatWindow chatWindow = new TcpChatWindow(destPort, listenPort);
}
}
上一篇:Android OpenGL ES 开发(N): OpenGL ES 2.0 机型兼容问题整理


下一篇:用Java实现多线程服务器程序